Java Stream: find an element with a min/max value of an attribute

后端 未结 9 1763
梦毁少年i
梦毁少年i 2020-12-06 15:58

I have a stream of objects and I would like to find the one with a maximal value of some attribute that\'s expensive to calculate.

As a specific simple example, say

9条回答
  •  星月不相逢
    2020-12-06 16:48

    How about using two streams, one to create a map with the pre-calculated values and a second using the map's entry set to find the max value:

            String coolestString = stringList
                .stream()
                .collect(Collectors.toMap(Function.identity(), Test::coolnessIndex))
                .entrySet()
                .stream()
                .max((s1, s2) -> Integer.compare(s1.getValue(), s2.getValue()))
                .orElse(null)
                .getKey();
    

提交回复
热议问题