Normally, before Java 8, when we want to sort the elements of a List in Java, we will use the Comparator object.
Eg:
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 27 |
package com.huongdanjava.javaexample; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Example { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Thanh"); names.add("Khanh"); names.add("Tan"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.compareTo(s2); } }); for (String s : names) { System.out.println(s); } } } |
Result:
From Java 8 onwards, we have another way of doing this. That is, using the sort() method of the List object with the Lambda Expression.
Now we can rewrite the above example with the sort() method and Lambda Expression:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.huongdanjava.javaexample; import java.util.ArrayList; import java.util.List; public class Example { public static void main(String[] args) { List<String> names = new ArrayList<>(); names.add("Thanh"); names.add("Khanh"); names.add("Tan"); names.sort((s1, s2) -> s1.compareTo(s2)); names.forEach(System.out::println); } } |
The parameter of the sort() method is a Comparator interface. Comparator interface is a Functional Interface so we can use Lambda Expression for it.
The result is the same: