我有以下数据结构:
Map<Integer, Map<String,Double>>
----------------
| | a 2 |
| 100 | b 1 |
| | c 2 |
----------------
| | a 2 |
| 101 | c 2 |
----------------
| | a 2 |
| 102 | b 1 |
| | c 2 |
----------------
目标:获取包含最大尺寸内部 map 的外部 map 的 ID。
例如,100
或 102
,它们都包含一个大小为 3 的内部映射。
例如,我如何使用 Stream API
?
最佳答案
map.values().stream().max(Comparator.comparingInt(Map::size)).get()
是你要找的。p>
map.keySet().stream().max(Comparator.comparingInt(k -> map.get(k).size()))
如果您想要 key 而不是 map ,则可以使用上面的方法。 测试代码:
Map<Integer, Map<String, Integer>> map = new HashMap<>();
Map<String, Integer> map2 = new HashMap<>();
map2.put("A", 1);
map2.put("B", 2);
map2.put("C", 3);
map.put(100, map2);
map2 = new HashMap<>();
map2.put("A", 1);
map2.put("B", 2);
map.put(101, map2);
System.out.println(map.values()
.stream()
.max(Comparator.comparingInt(Map::size)).get());
关于Java - 查找最大大小的哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220071/