Assume I have a Java Bean class which named Sentence
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(of = "id", callSuper = false)
public class Sentence implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Integer projectId;
private String text;
private Integer intentId;
}
Assume I have a List of Sentence which named result:
List<Sentence> result = new ArrayList<>();
If I would like to sort result by intendId, we can using Comparator to fulfill this requirement before Java 8
Collections.sort(result, new Comparator<Sentence>() {
@Override
public int compare(Sentence o1, Sentence o2) {
return o1.getIntentId().compareTo(o2.getIntentId());
}
});
In Java 8, we can take advantage of Lambda to cope with this requirement easily:
Collections.sort(result, (s1, s2) -> s1.getIntentId().compareTo(s2.getIntentId()));
Reference
[1] https://dzone.com/articles/dont-fear-the-lambda