我想用 Java 8 遍历 HashMap ,将其键与给定列表(包含具有键 ID 的对象)进行比较,并返回 HashMap 中的值,其中 HashMap 的键和对象的键列表是相等的。我想不通。
我尝试完成这样的事情:
someHashMap.entrySet()
.stream()
.filter(entry -> entry.getValue().equals(something.stream().iterator().next().getID()))
.map(map -> map.getValue())
.collect(Collectors.toList());
最佳答案
如果您初始化了这些对象:
Map<K,V> someHashMap;
List<K> something;
您可以像这样遍历 List
,从 Map
中获取值列表:
List<V> values = something.stream()
//.distinct() // include this if there may be duplicate keys
.filter(someHashMap::containsKey)
.map(someHashMap::get)
.collect(Collectors.toList());
或者,如果您想遍历 Map
(速度较慢),您可以使用:
List<V> values = someHashMap.entrySet()
.stream()
.filter(e -> something.contains(e.getKey()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
关于Java 8 检查其键的 HashMap 是否与包含键的列表相等,并返回它们相等的 HashMap 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43960080/