Normally, before Java 8, when we want to sort a List object, we will use Comparator object.
For example:
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:
Since Java 8, we have another way to do the sorting a List object. That is: using sort() method in List object with Lambda Expression.
Back to my example, I can re-write the code using sort() method and Lambda Expression as below:
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 argument of sort() method is a Comparator interface and because Comparator interface has just only one method, then we can call it is Functional Interface and apply Lambda Expression for it.
When we run again the example, we will get the same result as above.