Sắp xếp phần tử List bằng biểu thức lambda
Ví dụ
import java.util.*;
public class Demo{
public static void main(String[] args){
ArrayList<Integer> my_arr = new ArrayList<Integer>();
my_arr.add(190);
my_arr.add(267);
my_arr.add(12);
my_arr.add(0);
System.out.println("Trước sắp xếp, phần tử trong array list: " + my_arr);
Collections.sort(my_arr, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
System.out.println("Sau sắp xếp, phần tử trong array list: " + my_arr);
}
}
Kết quả
Trước sắp xếp, phần tử trong array list: [190, 267, 12, 0] Sau sắp xếp, phần tử trong array list: [267, 190, 12, 0]
Lớp Demo chứa hàm main. ArrayList tạo và phần tử thêm bằng add. Phần tử sắp xếp bằng sort và biểu thức điều kiện quyết định hiển thị tùy phần tử lớn hơn, nhỏ hơn hay bằng nhau.
Sắp xếp phần tử TreeMap bằng biểu thức lambda
Ví dụ
import java.util.*;
public class Demo{
public static void main(String[] args){
TreeMap<Integer, String> my_treemap = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0);
my_treemap.put(56, "Joe");
my_treemap.put(43, "Bill");
my_treemap.put(21, "Charolette");
my_treemap.put(33, "Jonas");
System.out.println("TreeMap chứa các phần tử: " + my_treemap);
}
}
Kết quả
TreeMap chứa các phần tử: {56=Joe, 43=Bill, 33=Jonas, 21=Charolette}
Lớp Demo chứa hàm main. TreeMap định nghĩa, biểu thức điều kiện viết ở đây. Phần tử thêm bằng put và in ra console.