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 that we have a list of strings and we want to find the coolest one, given a
coolnessIndex
String coolestString = stringList
.stream()
.max((s1, s2) -> Integer.compare(coolnessIndex(s1), coolnessIndex(s2)))
.orElse(null);
coolnessIndex
max
coolnessIndex
String coolestString = stringList
.stream()
.maxByAttribute(s -> coolnessIndex(s))
.orElse(null);
Stream
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 <K,V> Function<K,V> cache(Function<K,V> f, Map<K,V> cache)
{
return k -> cache.computeIfAbsent(k, f);
}
public static <K,V> Function<K,V> cache(Function<K,V> 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);