How to sort list of objects using multiple fields?
2 min readMay 10, 2022
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;}@Overridepublic 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:
- Anonymous Class
We can to make use of compare method in 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;@Overridepublic 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 firstNamelist.sort(Comparator.comparing((Student s) -> s.getStream()).thenComparing((Student s) -> s.getFirstName()));return list;}
Originally published at https://www.thecodecity.com on May 10, 2022.