We can sort list using multiple fields with Comparator. Here we are going to see two ways to do that.
Let’s say we have a Student class as below.
public class Student{
private int rollNum;
private String firstName;
private String stream;
public Student(int rollNum, String firstName, String stream) {
super();
this.rollNum = rollNum;
this.firstName = firstName;
this.stream = stream;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getRollNum() {
return rollNum;
}
public void setRollNum(int rollNum) {
this.rollNum = rollNum;
}
public String getStream() {
return stream;
}
public void setStream(String stream) {
this.stream = stream;
}
@Override
public String toString() {
return stream +" " +firstName +" "+ rollNum;
}
}
And a list of Students.
private List<Student> getStudentList() { return Arrays.asList(new Student(1, "Bindu", "IT"), new Student(2, "Sam", "CS"), new Student(3, "David", "IT"), new Student(4, "Anjali", "CS")); }
We can compare the list using multiple fields using two methods as below:
- Using anonymous class
We need to make use of Comparator interface to compare using multiple fields. Comparator is a functional interface, which mean it has only one abstract method compare. We are going to override this method in anonymous class.
private List<Student> sortWithAnymClass(List<Student> list) { Collections.sort(list, new Comparator<Student>() { // compare using stream and then rollNumber; @Override public int compare(Student s1, Student s2) { if (s1.getStream().equals(s2.getStream())) { if (s1.getRollNum() == s2.getRollNum()) return 0; if (s1.getRollNum() > s2.getRollNum()) return 1; return -1; } return s1.getStream().compareTo(s2.getStream()); } }); return list; }
2. Using lambda expression
private List<Student> sortWithLambdaExp(List<Student> list) { // sort using stream and firstName list.sort(Comparator.comparing((Student s) -> s.getStream()).thenComparing((Student s) -> s.getFirstName())); return list; }