I am trying to use a comparator to help sort a list of objects. I have a question about how exactly the comparator works and what it would be doing exactly in the following
Basically, you want to compare students by comparing some values that each maps to. This is usually done by
static Comparator comparator()
{
return Comparator.comparing( Foo::complexOperation );
}
However, since the function complexOperation is too expensive, we want to cache its results. We can have a general purpose utility method Function cache(Function)
static Comparator comparator()
{
return Comparator.comparing( cache(Foo::complexOperation) );
}
In general, it is better that the caller can supply a Map as the cache
public static Function cache(Function f, Map cache)
{
return k->cache.computeIfAbsent(k, f);
}
We can use IdentityHashMap as the default cache
public static Function cache(Function f)
{
return cache(f, new IdentityHashMap<>());
}