lambda函式是變成對集合進行排序的幾種方式
阿新 • • 發佈:2019-01-23
先來一個集合:
List<Point> points =
Arrays.asList(
new Point(1, 2),
new Point(3, 2),
new Point(4, 2),
new Point(2, 2)
);
方式一:
// 比較器方法
Comparator<Point> byX = new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
return Double.compare(p1.getX(), p2.getX());
}
};
方式二(最簡單):
Comparator<Point> byX = Comparator.comparing(Point::getX);
方式三(過時):
Comparator<Point> byX = (p1, p2) -> Double.compare(p1.getX(), p2.getX());
方式四:
Function<Point, Double> keyExtractor = point -> point.getX(); Comparator<Double> keyComparer = Double::compare; Comparator<Point> byX = (p1, p2) -> keyComparer.compare(keyExtractor.apply(p1), keyExtractor.apply(p2));
方式五(方式四的進階版推薦):
// 封裝一個比較的方法
public static <T,U extends Comparable<U>> Comparator<T> comparing(Function<T,U> keyExtractor){
return Comparator.comparing(keyExtractor::apply);
}
Function<Point, Double> keyExtractor = point -> point.getX();
Comparator<Point> byX = comparing(keyExtractor);
測試:
System.out.println("排序前:" + points);
points.sort(byX);
System.out.println("排序後:" + points);
測試結果:
排序前:
[java.awt.Point[x=1,y=2],
java.awt.Point[x=3,y=2],
java.awt.Point[x=4,y=2],
java.awt.Point[x=2,y=2]]
排序後:
[java.awt.Point[x=1,y=2],
java.awt.Point[x=2,y=2],
java.awt.Point[x=3,y=2],
java.awt.Point[x=4,y=2]]
本文參考:《精通lambda表示式:java多核程式設計》