【发布时间】:2021-05-16 11:38:59
【问题描述】:
我目前有一个“HashMap
我正在尝试在类中编写一个方法,该方法检索与其关联的值(项)最多的键(项),但不知道如何执行此操作,例如:
输入:
myItems.mostValues();
输出:
Item1 is has the most interactions, as it is connected to 3 items: {X, Y, Z}
【问题讨论】:
我目前有一个“HashMap
我正在尝试在类中编写一个方法,该方法检索与其关联的值(项)最多的键(项),但不知道如何执行此操作,例如:
输入:
myItems.mostValues();
输出:
Item1 is has the most interactions, as it is connected to 3 items: {X, Y, Z}
【问题讨论】:
注意:Sergei 的答案处理 null 并且是 O(n) 使用流。 Sergey的答案输出所有可能的值
size 或Set 反向排序
myItems.entrySet().stream().filter(e -> e.getValue() != null)
.sorted((a, b) -> b.getValue().size() - a.getValue().size())
.findFirst().orElse(new SimpleImmutableEntry<>(null, null))
.getValue());
int maxItem = 0;
Set<String> maxValues = null;
for (Map.Entry<String, Set<String>> e : myItems.entrySet()) {
if (e.getValue() == null) {
return null;
}
if (maxItem < e.getValue().size()) {
maxValues = e.getValue();
maxItem = maxValues.size();
}
}
以下代码假设初始 Map 不为空。
Map<String, Set<String>> myItems = new HashMap<>(); // input
myItems.put("a", new HashSet<>(Arrays.asList("a", "b", "c")));
myItems.put("b", new HashSet<>(Arrays.asList("b", "c")));
Set<String> result = myItems.values().stream()
.filter(Objects::nonNull) // get only non-null
.max(Comparator.comparing(Set::size)) // get the max size
.orElse(null); // avoid optional.get() error incase of no results - can use new HashSet<>() also
List
Map<String, Set<String>> myItems = new HashMap<>(); // input
myItems.put("a", new HashSet<>(Arrays.asList("a", "b", "c")));
myItems.put("b", new HashSet<>(Arrays.asList("x", "y", "z")));
myItems.put("c", new HashSet<>(Arrays.asList("a")));
List<Set<String>> result = new ArrayList<>();
myItems.values().stream()
.filter(Objects::nonNull) // get only non-null
.mapToInt(Set::size)
.max()
.ifPresent(val -> myItems.values().stream()
.filter(Objects::nonNull)
.filter(v -> v.size() == val)
.forEach(v -> result.add(v)));
:: 的方法引用,因为这有助于在需要时理解对象类型 (Set::size) 并为常见操作抽象类型 (Objects::nonNull)。【讨论】:
null 检查更新了答案。此外,将通过完整的检查添加任何未来的答案。感谢您抽出宝贵时间检查答案。
map.entrySet().stream()
.filter(entry -> entry.getValue() != null)
.max(Comparator.comparingInt(e -> e.getValue().size()))
.map(entry -> map.get(entry.getKey()));
【讨论】:
map.values()
.stream()
.filter(Objects::nonNull)
.mapToInt(val -> val.size())
.max()
.ifPresent(val-> map.keySet()
.stream()
.filter(key-> map.get(key) != null && map.get(key).size() == val)
.forEach(System.out::println)
);
【讨论】:
Sergeis 的回答,您可以在流后添加.filter(Objects::nonNull) 来处理null 以使其成为完整的答案。
ifPresent 中添加空检查,否则 map.get(key).size() 可能会抛出 NPE
e2 丢失。 Comparator.comparingInt(e -> e.getValue().size()) 可以使用,因为它不那么冗长