我正在尝试编写一个函数,它接收一个 Map 并返回一个 Entry。如果拥有最大 Integer 值的 entry 是唯一的,那么它应该返回该条 entry。但是,如果存在具有相同最大值的重复项,则应返回一个新的 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();
}
但是为了实现我最初说的那样,我只能找到一种解决方案,即创建一个初始流来进行布尔检查以查看是否存在多个最大值,如果不存在,则使用另一个流获取该值。 我希望找到一种解决方案,可以在一个流中完成这两个任务。
这是我的小测试案例:
@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());