java8排序

升序

List<Transaction> transactions = Arrays.asList(
                new Transaction(brian, 2011, 300),
                new Transaction(raoul, 2012, 1000),
                new Transaction(raoul, 2011, 400),
                new Transaction(mario, 2012, 710),
                new Transaction(mario, 2012, 700),
                new Transaction(alan, 2012, 950)
        );

//找出2011年发生的所有交易,并按交易额排序(从低到高)
List<Transaction> transactions1 = transactions.stream()
        .filter(t -> t.getYear() == 2011)
        .sorted(Comparator.comparingInt(Transaction::getValue))
        .collect(Collectors.toList());

降序

List<Transaction> transactions3 = transactions.stream()
                .filter(t -> t.getYear() == 2011)
                //Comparator.comparing默认是升序排序,用reversed改成降序
                .sorted(Comparator.comparing(Transaction::getValue).reversed())
                .collect(Collectors.toList());
posted @ 2023-12-22 16:12  SpecialSpeculator  阅读(15)  评论(0编辑  收藏  举报