How to force max to return ALL maximum values in a Java Stream?

后端 未结 7 862
陌清茗
陌清茗 2020-11-22 09:47

I\'ve tested a bit the max function on Java 8 lambdas and streams, and it seems that in case max is executed, even if more than one object compares

7条回答
  •  一生所求
    2020-11-22 09:59

    If you'd rather rely on a library than the other answers here, StreamEx has a collector to do this.

    Stream.of(1, 3, 5, 3, 2, 3, 5)
        .collect(MoreCollectors.maxAll())
        .forEach(System.out::println);
    

    There's a version which takes a Comparator too for streams of items which don't have a natural ordering (i.e. don't implement Comparable).

提交回复
热议问题