Today, i want to show you some Java 8 sort list by field examples. As you know, we were in a situation in which we wanted to sort a list by field or multiple fields. We can use Collector to resolve this issue. Comparator is used to sort a collection of objects which can be compared with each other.
Let’s dig deeper via examples:
We are considering the POJO and using it through all examples, below
1 2 3 4 5 6 7 |
public class People { public int age; public String gender; public String name; //getter and setter } |
1. Java 8 sort list by field
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class SortMultipleFields { public static void main(String args[]) { People a = new People(28, "M", "Mr A"); People b = new People(25, "M", "Mr B"); People c = new People(21, "M", "Mr C"); People d = new People(21, "M", "Mr D"); List<People> list = Arrays.asList(a, b, c, d); // Sort all Peoples by first name using lambda expression list.sort(Comparator.comparing(e -> e.getAge())); // OR you can use method reference list.sort(Comparator.comparing(People::getAge)); //And then reversed list.sort(Comparator.comparing(People::getAge).reversed()); // Let's print the sorted list list.forEach(System.out::println); } } |
Output
1 2 3 4 |
Mr A Gender:M 28 year olds Mr B Gender:M 25 year olds Mr C Gender:M 21 year olds Mr D Gender:M 21 year olds |
2. Java 8 sort list by multiple fields
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class SortMultipleFields2 { public static void main(String args[]) { People a = new People(28, "M", "Mr A"); People b = new People(25, "M", "Mr B"); People c = new People(29, "M", "Mr C"); People d = new People(21, "F", "Mr C"); List<People> list = Arrays.asList(a, b, c, d); // Sorting on multiple fields; Group by. list.sort(Comparator.comparing(People::getName).thenComparing(People::getAge)); // Let's print the sorted list list.forEach(System.out::println); } } |
Output
1 2 3 4 |
Mr A Gender:M 28 year olds Mr B Gender:M 25 year olds Mr C Gender:F 21 year olds Mr C Gender:M 29 year olds |
3. Java 8 parallel array sorting
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public class SortMultipleFields3 { public static void main(String args[]) { People a = new People(28, "M", "Mr A"); People b = new People(25, "M", "Mr B"); People c = new People(29, "M", "Mr C"); People d = new People(21, "F", "Mr C"); List<People> list = Arrays.asList(a, b, c, d); People[] array = list.stream().toArray(People[]::new); // Parallel sorting Arrays.parallelSort(array, Comparator.comparing(People::getName).thenComparing(People::getAge)); // Let's print the sorted list Arrays.stream(array).forEach(System.out::println); } } |
Output
That’s all about the Java 8 sort list by field examples.
References
Comparator (Java Platform SE 8 )
Download the complete source code, click below
SortByMultipleFields.zip (282 downloads)