--Comparator can be used for convenient sorting.
import java.util.*;
class Solution {
public static void main(String[] args) {
sort1();
sort2();
}
public static void sort1 () {
List<Integer> list1 = Arrays.asList(3,2,8,4);
System.out.println("Before sort: "+list1);
Comparator<Integer> comparator = new Comparator<Integer>() {
public int compare(Integer int1, Integer int2) {
return (int1.compareTo(int2));
}
};
Collections.sort(list1, comparator);
System.out.println("comparator(Instantiate),After sort: "+list1);
}
public static void sort2(){
List<Integer> list1 = Arrays.asList(3,2,8,4);
System.out.println("Before sort: "+list1);
Collections.sort(list1, (a, b) -> Integer.compare(a, b));
System.out.println("Lambda-style comparator,After sort: "+list1);
}
}
Before sort: [3, 2, 8, 4]
comparator(Instantiate),After sort: [2, 3, 4, 8]
Before sort: [3, 2, 8, 4]
Lambda-style comparator,After sort: [2, 3, 4, 8]
Recommended Posts