我正在尝试编写一个接收 Map 并返回 Entry 的函数。如果具有最大整数值的条目是唯一的,则应返回该条目。但是,如果存在具有相同最大值的重复条目,它应该返回一个键为“MULTIPLE”且值为 0 的新条目。我很容易获得忽略重复项的最大值:
public static Entry<String,Integer> getMax(Map<String,Integer> map1) {
return map1.entrySet().stream()
.max((a,b) -> a.getValue().compareTo(b.getValue()))
.get();
}
但是为了让我按照我最初所说的去做,我只能找到一个解决方案,我必须创建一个初始流来执行 bool 值检查是否有多个最大值,如果没有得到值,则执行另一个流。我想找到一种解决方案,我可以只用一个流来完成这两项任务。
这是我的小测试用例:
@Test
public void test1() {
Map<String,Integer> map1 = new HashMap<>();
map1.put("A", 100);
map1.put("B", 100);
map1.put("C", 100);
map1.put("D", 105);
Assert.assertEquals("D", getMax(map1).getKey());
Map<String,Integer> map2 = new HashMap<>();
map2.put("A", 100);
map2.put("B", 105);
map2.put("C", 100);
map2.put("D", 105);
Assert.assertEquals("MULTIPLE", getMax(map2).getKey());
最佳答案
这是一个简单的归约案例,您不需要任何外部库。
Map.Entry<String, Integer> max(Map<String, Integer> map) {
return map.entrySet().stream()
.reduce((e1, e2) -> {
if (e1.getValue() == e2.getValue()) {
return new SimpleImmutableEntry<>("MULTIPLE", 0);
} else {
return Collections.max(asList(e1, e2), comparingInt(Map.Entry::getValue));
}
})
.orElse(new SimpleImmutableEntry<>("NOT_FOUND", 0));
}
关于java-8 - Java 流 : get max if no duplicates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45623951/