我如何将二维数组收集到映射< string,set< gt;>?

发布于 2025-01-25 20:45:03 字数 597 浏览 5 评论 0原文

我有两个字符串的数组。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

小草泠泠 2025-02-01 20:45:04

您可以使用collector.mapping()toset() downstream:

Collectors.groupingBy(a -> a[0],
    Collectors.mapping(v -> v[1], Collectors.toSet()))

它产生{a = [1,2],b = [3]} < /代码>。第一个将流元素映射到数组的第二个元素,然后将其作为映射到组密钥的集合收集。

You can use Collectors.mapping() with a toSet() downstream:

Collectors.groupingBy(a -> a[0],
    Collectors.mapping(v -> v[1], Collectors.toSet()))

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.

七禾 2025-02-01 20:45:04

使用collectors.groupingbycollectors.mapping.mapping()

public static void main(String[] args) {
    var array = new String[][]{
        {"a", "1"},
        {"a", "2"},
        {"b", "3"}
    };

    Map<String, Set<String>> result =
        Stream.of(array)
            .collect(Collectors.groupingBy(arr -> arr[0],
                Collectors.mapping(arr -> arr[1],
                    Collectors.toSet())));

    System.out.println(result);
}

这样做的另一种方法是使用collector.of()

Map<String, Set<String>> result =
    Stream.of(array)
        .collect(Collector.of(
            HashMap::new,
            (Map<String, Set<String>> map, String[] arr) ->
                map.computeIfAbsent(arr[0], k -> new HashSet<>()).add(arr[1]),
            (Map<String, Set<String>> left, Map<String, Set<String>> right) ->
                { left.putAll(right); return left; }));

输出

{a=[1, 2], b=[3]}

Use Collectors.groupingBy in conjuction with Collectors.mapping().

public static void main(String[] args) {
    var array = new String[][]{
        {"a", "1"},
        {"a", "2"},
        {"b", "3"}
    };

    Map<String, Set<String>> result =
        Stream.of(array)
            .collect(Collectors.groupingBy(arr -> arr[0],
                Collectors.mapping(arr -> arr[1],
                    Collectors.toSet())));

    System.out.println(result);
}

Another way of doing this is to utilize Collector.of():

Map<String, Set<String>> result =
    Stream.of(array)
        .collect(Collector.of(
            HashMap::new,
            (Map<String, Set<String>> map, String[] arr) ->
                map.computeIfAbsent(arr[0], k -> new HashSet<>()).add(arr[1]),
            (Map<String, Set<String>> left, Map<String, Set<String>> right) ->
                { left.putAll(right); return left; }));

Output

{a=[1, 2], b=[3]}
酒解孤独 2025-02-01 20:45:04

您需要一个collector.mapping(也无需指定string []内部)

var array = new String[][]{{"a", "1"}, {"a", "2"}, {"b", "3"},};

Map<String, Set<String>> res = Arrays.stream(array).collect(Collectors.groupingBy(
        a -> a[0],
        Collectors.mapping(a -> a[1], Collectors.toSet())
));

System.out.println(res); // {a=[1, 2], b=[3]}

You need a Collectors.mapping (also you don't need to specify String[] inside)

var array = new String[][]{{"a", "1"}, {"a", "2"}, {"b", "3"},};

Map<String, Set<String>> res = Arrays.stream(array).collect(Collectors.groupingBy(
        a -> a[0],
        Collectors.mapping(a -> a[1], Collectors.toSet())
));

System.out.println(res); // {a=[1, 2], b=[3]}
迷迭香的记忆 2025-02-01 20:45:04

您可以简单地使用for-east循环

   Map<String, Set<String>> map=new HashMap<>();
   for(String []arr : array){
     Set<String> set = map.getOrDefault(arr[0], new HashSet<>());
     set.add(arr[1]);
     map.put(arr[0],set);
   }
   System.out.println(map);
 

输出:

{a = [1,2],b = [3]}

You can simply do this by using for-each loop

   Map<String, Set<String>> map=new HashMap<>();
   for(String []arr : array){
     Set<String> set = map.getOrDefault(arr[0], new HashSet<>());
     set.add(arr[1]);
     map.put(arr[0],set);
   }
   System.out.println(map);
 

Output :

{a=[1, 2], b=[3]}

苏佲洛 2025-02-01 20:45:04

您可以使用collector.tomap而不是collector.groupingby

public class Main {

  public static void main(String[] args) throws Exception {
    String[][] array = new String[][]{{"a", "1"}, {"a", "2"}, {"b", "3"}};
    Map<String, Set<String>> map = Arrays.stream(array).collect(Collectors.toMap(
            arr -> arr[0],
            arr -> new HashSet<>(Collections.singleton(arr[1])),
            (l, r) -> {
              l.addAll(r);
              return l;
            }));
    System.out.println(map);
  }
}

第一个参数为keymapper,第二个是valuemapper,第三 - MergeFunction

Instead of Collectors.groupingBy, you could use Collectors.toMap.

public class Main {

  public static void main(String[] args) throws Exception {
    String[][] array = new String[][]{{"a", "1"}, {"a", "2"}, {"b", "3"}};
    Map<String, Set<String>> map = Arrays.stream(array).collect(Collectors.toMap(
            arr -> arr[0],
            arr -> new HashSet<>(Collections.singleton(arr[1])),
            (l, r) -> {
              l.addAll(r);
              return l;
            }));
    System.out.println(map);
  }
}

First parameter is keyMapper, second is valueMapper, third - mergeFunction.

记忆之渊 2025-02-01 20:45:04

您可以循环遍历数组,对于每个字符,您可以检查此键是否保存在地图之前,如果是的,则只需将相应的字符推到该重复键的列表中

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文