Efficiency of the way comparator works

前端 未结 2 2014
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 08:21

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

2条回答
  •  我在风中等你
    2021-01-06 09:10

    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<>());
    }
    

提交回复
热议问题