I have the following two classes:
class KeyClass {
private prop1;
private prop2;
hashcode() {
//implemented properly
}
equals() {
//implemented properly
}
}
class ValueClass {
private prop1;
private prop2;
hashcode() {
//implemented properly
}
equals() {
//implemented properly
}
}
I am trying to find out the max pair from a map where objects of these classes are key and value pairs respectively. I also have an com.google.common.collect.Ordering<ValueClass>
which uses multiple comparators. I can easily find out the max of values using this ordering, but what I am interested into is the key of the max value.
I can write a certain implementation wherein I can keep track of my key w.r.t the value in a loop and use the ordering to compare values (similar to the conventional way of finding a max value) but I want to know if we already have such case handled by Guava
or any other library?
You say guava or any other library and that's straightforward with Java 8 streams. If your Ordering<ValueClass>
instance is called ordering
:
Entry<KeyClass, ValueClass> maxEntry = map.entrySet().stream()
.max(Comparator.comparing(Entry::getValue, ordering))
.orElse(null);
Add .map(Entry::getKey)
before orElse
to get just the key.
The above is possible since guava's Ordering
implements java.util.Comparator
so you can pass it as argument to comparing.