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

后端 未结 9 1765
梦毁少年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:45

    Here's a variant using an Object[] as a tuple, not the prettiest code but concise

    String coolestString = stringList
            .stream()
            .map(s -> new Object[] {s, coolnessIndex(s)})
            .max(Comparator.comparingInt(a -> (int)a[1]))
            .map(a -> (String)a[0])
            .orElse(null);
    

提交回复
热议问题