java1.8 的新的函數式的 Comparator 不要太方便了. 可以輕鬆的實現各種List 的排序, 比以前寫什麼匿名的內部類, 靜態類方便了很多, 很多.
//比較器
//按照sort_id 的升序排
//寫法1
Comparator<ApplyedPersonVO> c = (a, b) -> a.getSort_id().compareTo(b.getSort_id());
//寫法2
Comparator<ApplyedPersonVO> c2=Comparator.comparing(ApplyedPersonVO::getSort_id);
//寫法3
Comparator<ApplyedPersonVO> c3=Comparator.comparing(a->a.getSort_id());
//默認是升序
Collections.sort(coniditionVOS, Comparator.comparing(ApprovalPersonVO.ConiditionVO::getCondtion_value));
//加上reversed()就是降序了
Collections.sort(coniditionVOS, Comparator.comparing(ApprovalPersonVO.ConiditionVO::getCondtion_value).reversed());
//演示的示例
//升序
List<Integer> list = Arrays.asList(1, 4, 2, 6, 2, 8);
list.sort(Comparator.naturalOrder());
//降序
List<Integer> list = Arrays.asList(1, 4, 2, 6, 2, 8);
list.sort(Comparator.reverseOrder());
List<Computer> list = new ArrayList<>();
list.add(new Computer("xiaomi",4000,6));
list.add(new Computer("sony",5000,4));
list.add(new Computer("dell",4000,5));
list.add(new Computer("mac",6000,8));
list.add(new Computer("micro",5000,6));
// 先以價格(升序)、後再速度(升序)
list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed));
// 先以速度(降序)、後再價格(升序)
list.sort(Comparator.comparingInt(Computer::getSpeed).reversed().thenComparingInt(Computer::getPrice));
// 先以價格(降序)、後再速度(降序)
list.sort(Comparator.comparingInt(Computer::getPrice).thenComparingInt(Computer::getSpeed).reversed());
@Data
public static class Computer {
private String name;
private Integer price;
private Integer speed;
}
源碼是:
import java.util.Comparator;
public class Demo {
public static void main(String[] args) {
Comparator<TimetableInfo> c = Comparator.comparing(TimetableInfo::getTotalTime);
}
}
編譯之後是: