List自定义排序和流式API排序

自定义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}]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值