我如何将二维数组收集到映射< string,set< gt;>?
我有两个字符串的数组。
var array = new String[][]{
{"a", "1"},
{"a", "2"},
{"b", "3"},
...
};
如何将上述数组收集到map< string,set< string>>
谁的键是每个数组的第一个元素,而值是数组的第二个元素集?
这样我得到了关注地图?
// Map<String, Set<String>>
<"a", ["1, "2"]>,
<"b", ["3"]>,
...
到目前为止,我发现我可以这样对每个数组的第一个元素进行分类。
Arrays.stream(array).collect(Collectors.groupingBy(
a -> ((String[])a)[0],
// how can I collect the downstream?
);
I have an array of arrays of two strings.
var array = new String[][]{
{"a", "1"},
{"a", "2"},
{"b", "3"},
...
};
How can I collect the above array into a Map<String, Set<String>>
whose key is the first element of each array and the value is a set of second elements of the array?
So that I get following map?
// Map<String, Set<String>>
<"a", ["1, "2"]>,
<"b", ["3"]>,
...
So far, I found I can classify the first element of each array like this.
Arrays.stream(array).collect(Collectors.groupingBy(
a -> ((String[])a)[0],
// how can I collect the downstream?
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用
collector.mapping()
与toset()
downstream:它产生
{a = [1,2],b = [3]} < /代码>。第一个将流元素映射到数组的第二个元素,然后将其作为映射到组密钥的集合收集。
You can use
Collectors.mapping()
with atoSet()
downstream:Which produces
{a=[1, 2], b=[3]}
. That first maps stream elements to the array's second element, then collects those as a set mapped to the group key.使用
collectors.groupingby
与collectors.mapping.mapping()
。这样做的另一种方法是使用
collector.of()
:输出
Use
Collectors.groupingBy
in conjuction withCollectors.mapping()
.Another way of doing this is to utilize
Collector.of()
:Output
您需要一个
collector.mapping
(也无需指定string []
内部)You need a
Collectors.mapping
(also you don't need to specifyString[]
inside)您可以简单地使用for-east循环
输出:
{a = [1,2],b = [3]}
You can simply do this by using for-each loop
Output :
{a=[1, 2], b=[3]}
您可以使用
collector.tomap
而不是collector.groupingby
。第一个参数为
keymapper
,第二个是valuemapper
,第三 -MergeFunction
。Instead of
Collectors.groupingBy
, you could useCollectors.toMap
.First parameter is
keyMapper
, second isvalueMapper
, third -mergeFunction
.您可以循环遍历数组,对于每个字符,您可以检查此键是否保存在地图之前,如果是的,则只需将相应的字符推到该重复键的列表中
You can loop through your array and for every character you can check if this key is saved before in your map, if yes just push the corresponding character to the list of that repeated key