Search code examples
lambdajava-8comparatortreemap

Which is faster? Using a custom Comparator class or lambda function


I am trying to create a sorted map in java (sorted in decreasing order of key). I tried

Map<Integer,Integer> map = new TreeMap<>((a,b)->(b-a));

Would it create any performance impact if I write a Comparator class for the same task?


Solution

  • You will never feel a difference between creating a class explicitly and when then runtime will create one for you, implicitly via the lambda expression.

    What you might want to improve is the readability of your code, wouldn't this be much easier to understand?

    new TreeMap<>(Comparator.reverseOrder());