【问题标题】:Java streams for adding to a list if it exists or creating a new one in a HashMap [duplicate]用于添加到列表(如果存在)或在 HashMap 中创建新列表的 Java 流 [重复]
【发布时间】:2021-01-27 21:44:02
【问题描述】:

我有一个必须使用分隔符拆分的字符串列表,然后获取拆分的第二个值以创建字符串数组的映射。

这是一个例子:

如下字符串列表:

["item1:parent1", "item2:parent1", "item3:parent2"]

应转换为具有以下条目的地图:

<key: "parent1", value: ["item1", "item2"]>,
<key: "parent2", value: ["item3"]>

我尝试遵循question 中给出的解决方案,但没有成功

示例代码:

var x = new ArrayList<>(List.of("item1:parent1", "item2:parent1", "item3:parent2"));
var res = x.stream().map(s->s.split(":")).collect(Collectors.groupingBy(???));

【问题讨论】:

    标签: java stream


    【解决方案1】:

    @Eritrean has shown 如何处理流。这是另一种方式:

    Map<String, List<String>> result = new LinkedHashMap<>();
    x.forEach(it -> {
        String[] split = it.split(":");
        result.computeIfAbsent(split[1], k -> new ArrayList<>()).add(split[0]);
    });
    

    这使用Map.computeIfAbsent,在这种情况下会派上用场。

    【讨论】:

      【解决方案2】:

      假设拆分后的数组的长度始终为 2,如下所示应该可以工作

      var list = List.of("item1:parent1", "item2:parent1", "item3:parent2");
      var map = list.stream()
                  .map(s -> s.split(":"))
                  .collect(Collectors.groupingBy(
                          s -> s[1], 
                          Collectors.mapping(s -> s[0],  Collectors.toList())));
          
      System.out.println(map);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-20
        • 1970-01-01
        相关资源
        最近更新 更多