在Java8中,当在流中复制键时,如何收集到形成值列表的映射中
我有一个二维数组或在Java8中,当在流中复制键时,如何收集到形成值列表的映射中,java,java-8,hashmap,java-stream,Java,Java 8,Hashmap,Java Stream,我有一个二维数组或EntrySet形式的元素流。我需要在地图中收集这些信息。现在的问题是元素流可能有重复的元素。假设我希望该值是一个列表: Map<String,List<String>> 我想有一个方法在哪里 我可以操作e->e[0]和e->e[1]来解决问题。可能吗?为此,我需要访问正在收集的当前地图对象。我不确定这是否有意义 这是一种使用Java8流实现的方法 预期产出: 这就是groupingBy的作用: Map<String,List<String
EntrySet
形式的元素流。我需要在地图
中收集这些信息。现在的问题是元素流可能有重复的元素。假设我希望该值是一个列表:
Map<String,List<String>>
我想有一个方法在哪里
e->e[0]
和e->e[1]
来解决问题。可能吗?为此,我需要访问正在收集的当前地图对象。我不确定这是否有意义这就是
groupingBy
的作用:
Map<String,List<String>> vehicle =
stream.collect(Collectors.groupingBy(e -> e[0],
Collectors.mapping(e -> e[1],
Collectors.toList())));
您可以使用
groupingBy
getMapStream()
.map(item -> Arrays.asList(item))
.collect(Collectors.groupingBy(l->l.get(0),
Collectors.mapping(l1->l1.get(1),Collectors.toList())));
或者使用带有合并功能的toMap()
Map<String,List<String>> vehicle = getMapStream()
.collect(Collectors.toMap(item->item[0],
item->new ArrayList<>(Arrays.asList(item[1])),
(l1,l2)->{l1.addAll(l2);return l1;}));
Map vehicle=getMapStream()
.collect(收集器.toMap)(项目->项目[0],
项目->新建ArrayList(Arrays.asList(项目[1]),
(l1,l2)->{l1.addAll(l2);返回l1;});
所以在toMap中,我们传递的第三个参数是merge函数。对的方法也不错:)
Map<String,List<String>> vehicle =
stream.collect(Collectors.groupingBy(e -> e[0],
Collectors.mapping(e -> e[1],
Collectors.toList())));
{CAR=[Audi], BIKE=[Harley Davidson, Pulsar]}
getMapStream()
.map(item -> Arrays.asList(item))
.collect(Collectors.groupingBy(l->l.get(0),
Collectors.mapping(l1->l1.get(1),Collectors.toList())));
Map<String,List<String>> vehicle = getMapStream()
.collect(Collectors.toMap(item->item[0],
item->new ArrayList<>(Arrays.asList(item[1])),
(l1,l2)->{l1.addAll(l2);return l1;}));