Java – find hash table with maximum size
•
Java
I have the following data structures:
Map<Integer,Map<String,Double>> ---------------- | | a 2 | | 100 | b 1 | | | c 2 | ---------------- | | a 2 | | 101 | c 2 | ---------------- | | a 2 | | 102 | b 1 | | | c 2 | ----------------@H_419_12@目标:获取包含具有最大大小的内部地图的外部地图的ID.
例如,100或102,两者都包含大小为3的内部地图.
例如,我如何使用Stream API?
Solution
This should output 100 or the key with the largest element
map.keySet().stream().max((v1,v2) -> {
return Integer.compare(map.get(v1).size(),map.get(v2).size());
})@H_419_12@
或使用比较器
map.keySet().stream().max(Comparator.comparingInt(v -> map.get(v).size()))@H_419_12@
完整代码:
Map<Integer,Double>> map = new HashMap<>();
Map<String,Double> map100 = new HashMap<>();
map100.put("a",2.0);
map100.put("b",1.0);
map100.put("c",2.0);
Map<String,Double> map101 = new HashMap<>();
map101.put("a",2.0);
map101.put("b",1.0);
Map<String,Double> map102 = new HashMap<>();
map102.put("a",2.0);
map102.put("b",1.0);
map102.put("c",2.0);
map102.put("d",2.0);
map.put(100,map100);
map.put(101,map101);
map.put(102,map102);
System.out.println(map.keySet().stream().max(Comparator.comparingInt(v -> map.get(v).size())));
System.out.println(map.keySet().stream().max((v1,v2) -> {
return Integer.compare(map.get(v1).size(),map.get(v2).size());
}));@H_419_12@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
