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… Read More