A BinaryOperator not a good specification for this task, it is straightforward to use in recovery to obtain the corresponding value, for example. minimum or maximum, however, it is not suitable for returning a bound value, such as the value of the Map s key. Using this method implies that the implementation must perform additional operations to find out what BinaryOperator really did in order to select the correct key value during the reduction. Worse, it cannot guarantee that BinaryOperator doing something that allows this kind of reduction, for example. an operator can return a value that is not one of its arguments.
For such a task, a Comparator is the best choice because it is designed to indicate the order and perform related operations, such as finding maximum and minimum. An implementation might look like this:
public static Pair<String,Double> getMinimumKeyValue( Map<String, List<Double>> map, Comparator<Double> function) { return map.entrySet().stream() .map(e->new Pair<>(e.getKey(), e.getValue().stream().min(function).get())) .min(Comparator.comparing(Pair::getRight, function)).get(); }
It is called getMinimumKeyValue , since it will return the minimum key / value pair when passed to Comparator.naturalOrder() .
But you can get the most by going through Comparator.reverseOrder() .
And it is easy to modify to support a wider range of use cases:
public static <K,V> Pair<K,V> getMinKeyValue( Map<K, ? extends Collection<V>> map, Comparator<? super V> function) { return map.entrySet().stream() .map(e->new Pair<>(e.getKey(), e.getValue().stream().min(function).get())) .min(Comparator.comparing(Pair::getRight, function)).get(); }
This still works to get Pair<String,Double> from Map<String, List<Double>> , but can do a lot more ...