我有一个包含 N 个哈希表的哈希表:
Map<Integer,Map<String,Double>
我需要创建一个包含内部映射的所有键的列表:
----------------
| | a 2 |
| 100 | b 1 |
| | c 2 |
----------------
| | a 2 |
| 101 | d 2 |
----------------
| | a 2 |
| 102 | b 1 |
| | e 2 |
----------------
列表 = {a,b,c,d,e}
这是我当前的代码:
Set<String> keys= new HashSet<>();
map1.entrySet().forEach(e -> {
keys.addAll(e.getValue().keySet());
});
map1 包含数千个条目。
这是最佳方法吗?有人知道更快的方法吗?
最佳答案
您可以尝试使用以下代码:
Map<String, Double> innerMap = new HashMap<>();
innerMap.put("a", 2d);
innerMap.put("b", 2d);
innerMap.put("c", 2d);
Map<String, Double> innerMap2 = new HashMap<>();
innerMap2.put("a", 2d);
innerMap2.put("d", 2d);
innerMap2.put("e", 2d);
Map<Integer, Map<String, Double>> map = new HashMap<>();
map.put(100, innerMap);
map.put(101, innerMap2);
Set<String> collect = map.values()
.stream()
.parallel()
.map(Map::keySet)
.flatMap(Collection::stream)
.collect(Collectors.toSet());
<小时/>
不幸的是,如果它对性能有显着影响,您将必须亲自尝试。
<小时/>这意味着您正在使用Java 8。但当您使用方法 forEach()
时,我只是假设是这样。
关于java - N个哈希表的键之间进行UNION操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41222448/