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

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

    Thanks everyone for suggestions. At last I found the solution I like the most at Efficiency of the way comparator works -- the answer from bayou.io:

    Have a general purpose cache method:

    public static  Function cache(Function f, Map cache)
    {
        return k -> cache.computeIfAbsent(k, f);
    }
    
    public static  Function cache(Function f)
    {
        return cache(f, new IdentityHashMap<>());
    }
    

    This could then be used as follows:

    String coolestString = stringList
            .stream()
            .max(Comparator.comparing(cache(CoolUtil::coolnessIndex)))
            .orElse(null);
    

提交回复
热议问题