自定义Point类
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getDistance() {
return x * x + y * y;
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
初始化List
List<Point> list = Stream.of(new Point(4, 2), new Point(1, 7), new Point(3, 5))
.collect(Collectors.toList());
输出结果
[Point{x=4, y=2}, Point{x=1, y=7}, Point{x=3, y=5}]
根据x进行排序
自定义Comparator排序
list.sort(new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
return p1.getX() - p2.getY();
}
});
lambda表达式写法
list.sort((p1, p2) -> p1.getX() - p2.getX());
使用自带的Comparator
list.sort(Comparator.comparingInt(Point::getX));
以上均输出
[Point{x=4, y=2}, Point{x=3, y=5}, Point{x=1, y=7}]
根据Point到原点距离排序
list.sort(Comparator.comparingInt(Point::getDistance));
也可这样写
list.sort(Comparator.comparingInt(p -> p.x * p.x + p.y * p.y));
以上comparingInt和comparing均可
输出结果
[Point{x=4, y=2}, Point{x=3, y=5}, Point{x=1, y=7}]
流式API写法
List<Point> sortedList = list.stream()
.sorted(Comparator.comparing(Point::getX))
.collect(Collectors.toList());
System.out.println(sortedList);
List<Point> reversedList = list.stream()
.sorted(Comparator.comparing(Point::getX).reversed())
.collect(Collectors.toList());
System.out.println(reversedList);
输出结果
[Point{x=1, y=7}, Point{x=3, y=5}, Point{x=4, y=2}]
[Point{x=4, y=2}, Point{x=3, y=5}, Point{x=1, y=7}]