BinaryOperator 不是该任务的良好规范,它可以直接用于归约以产生适当的值,例如最小值或最大值,但它不适合返回关联值,例如 Map 的键值。以这种方式使用它意味着实现必须执行额外的操作来找出BinaryOperator 实际做了什么,以便在减少期间选择正确的键值。更糟糕的是,它不能保证BinaryOperator 做了一些允许执行这种减少的事情,例如运算符可能返回一个既不是它的参数的值。
对于这样的任务,Comparator 是更好的选择,因为它旨在指定排序并执行相关操作,例如查找最大值和最小值。实现可能如下所示:
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();
}
它被命名为getMinimumKeyValue,因为它会在你传入Comparator.naturalOrder()时返回最小的键/值对。
但是你也可以通过Comparator.reverseOrder()获得最大值。
而且它很容易修改以支持更广泛的用例:
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();
}
这仍然适用于从Map<String, List<Double>> 中获取Pair<String,Double>,但可以做更多事情......