在Java8中,如何将列表的hashmap转换为单个列表?
我对Java8是完全陌生的,对于如何继续我有点不清楚。 在Java7中,我有一个映射在Java8中,如何将列表的hashmap转换为单个列表?,java,dictionary,streaming,flatmap,Java,Dictionary,Streaming,Flatmap,我对Java8是完全陌生的,对于如何继续我有点不清楚。 在Java7中,我有一个映射,我只会在键上使用for循环,并将列表收集到单个列表中 然而,我希望能在8小时内做到这一点。 我得到的是: List<Value> newList = resultMap.entrySet().stream() .flatMap( e -> e.getValue().stream()) .map( //
,我只会在键上使用for循环,并将列表收集到单个列表中
然而,我希望能在8小时内做到这一点。
我得到的是:
List<Value> newList = resultMap.entrySet().stream()
.flatMap( e -> e.getValue().stream())
.map( // get the value in the list)
.collect(Collectors.toList())
List newList=resultMap.entrySet().stream()
.flatMap(e->e.getValue().stream())
.map(//获取列表中的值)
.collect(收集器.toList())
但是,在本例中,我无法从hashmap中知道该值所属的键
执行上述操作时,如何获取
hashmap
的键值?您可以执行以下操作:
Map<Key, List<Value>> map = ...;
List<Map.Entry<Key, Value>> list =
map.entrySet()
.stream()
.flatMap(e -> {
return e.getValue().stream()
.map(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v));
})
.collect(Collectors.toList());
Map=。。。;
列表=
map.entrySet()
.stream()
.flatMap(e->{
返回e.getValue().stream()
.map(v->newAbstractMap.SimpleEntry(e.getKey(),v));
})
.collect(Collectors.toList());
这将为每个子列表中的每个值创建一个条目,其中键是该值来自的列表的对应键。您可以执行以下操作:
Map<Key, List<Value>> map = ...;
List<Map.Entry<Key, Value>> list =
map.entrySet()
.stream()
.flatMap(e -> {
return e.getValue().stream()
.map(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v));
})
.collect(Collectors.toList());
Map=。。。;
列表=
map.entrySet()
.stream()
.flatMap(e->{
返回e.getValue().stream()
.map(v->newAbstractMap.SimpleEntry(e.getKey(),v));
})
.collect(Collectors.toList());
这将为每个子列表中的每个值创建一个条目,其中键是该值来自的列表的对应键。for循环中的代码是什么样子的?我想知道如何使用该键,因为您没有将其放入结果列表中。对于这些键,您将使用
keySet
而不是entrySet
;请澄清resultMap
的类型以及您希望在newList
中看到的内容List values=map.entrySet().stream().map(map.Entry::getValue).collect(collector.toList())
@CardinalSystem OP说地图的类型应该类似于Map。在您放弃钥匙后,您无法取回钥匙。您的flatMap
lambda以后必须保留您想要的任何信息。for循环中的代码是什么样子的?我想知道如何使用该键,因为您没有将其放入结果列表中。对于这些键,您将使用keySet
而不是entrySet
;请澄清resultMap
的类型以及您希望在newList
中看到的内容List values=map.entrySet().stream().map(map.Entry::getValue).collect(collector.toList())
@CardinalSystem OP说地图的类型应该类似于Map。在您放弃钥匙后,您无法取回钥匙。您的flatMap
lambda必须保留您以后需要的任何信息。