Plog
Plog

Reputation: 9622

Java 8: Using Comparator.comparing when comparing values from a map based on given keys

I have written a comparator which compares string keys based on the value they correspond to in a predefined map.

 private Comparator<String> periodComparator() {
    return (s1, s2) -> {
      return periodMap.get(s1).compareTo(periodMap.get(s2));
    };
  }

However, IntelliJ is highlighting this to tell me that it can be replaced by Comparator.comparing (or something similar). I can't see how this could be possible. Is IntelliJ flagging up a false positive here or is there really a more succinct way to do this using Java 8 magic?

Upvotes: 1

Views: 992

Answers (3)

whatamidoingwithmylife
whatamidoingwithmylife

Reputation: 1186

If you are using IntelliJ and it suggests that it can be replaced, simply move your mouse cursor to the line in question (to the code in question) and press Alt + Enter, you will get a menu of options, one of them will be to replace your current code with what IntelliJ suggests, so just do that and you will see how it's supposed to be based on IDEA's suggestion.

Will EDIT and add pictures.

Example:

enter image description here

After you press Alt + Enter:

enter image description here

After you finally select for IntelliJ to replace your code, final result is:

enter image description here

So there you go.

Upvotes: 3

snap
snap

Reputation: 1915

The Comparator is a functional interface. So it has only one not static or default method to overwritte.

You use generics to tell the function what kind of objects should be compared. Then you only need to give in a lamda function to define the real comparsion logic.

All other functionality is defined by default methods (that's the magic ;))

Upvotes: 1

Chirlo
Chirlo

Reputation: 6132

This should do it:

Comparator<String> periodComparator = Comparator.comparing(periodMap::get)

Or as a method, same thing:

private Comparator<String> periodComparator(){
  return Comparator.comparing(periodMap::get);
}

Upvotes: 4

Related Questions