【问题标题】:Split element of list on delimiter. Store original element as key and list of split substrings as value in hashmap [closed]在分隔符上拆分列表元素。将原始元素存储为键,将拆分子字符串列表存储为哈希图中的值[关闭]
【发布时间】:2020-09-08 05:21:26
【问题描述】:

我有一个清单: "Cust_Gnrc_Activity","MRkt_Cust","Indivdl_GNRC_Acct", "Opty_Act"

我想拆分“_”上的每个元素,并将原始元素存储为 hashmap 的键,并将拆分的元素存储为值。

期望的结果: {"Cust_Gnrc_Activity":["Cust","Gnrc","Activity"], "Mrkt_Cust":["Mrkt", "Cust"]}等等...

【问题讨论】:

    标签: java arrays collections hashmap


    【解决方案1】:

    类似的东西:

    source.stream()
          .collect(toMap(Function.identity(), e -> e.split("_"))); // Map<String, String[]>
    

    或者如果您希望将值作为 List&lt;String&gt;:

    source.stream()
          .collect(toMap(Function.identity(), 
                           e -> Arrays.stream(e.split("_"))
                                      .collect(toList()))); // Map<String, List<String>>
    

    【讨论】:

      【解决方案2】:

      您可以使用 Stream API 来做到这一点:

      list.stream() // stream over List
              // split by "_" and convert it to List<String>
              .collect(Collectors.toMap(s -> s, s -> Arrays.asList(s.split("_"))));
      

      对于HashMap&lt;String, List&lt;String&gt;&gt;

      list.stream()
              .collect(HashMap::new,
                      (hm, s) -> hm.put(s, Arrays.asList(s.split("_"))),
                      (hm1, hm2) -> hm1.putAll(hm2));
      

      【讨论】:

        【解决方案3】:

        尝试使用这个:

        Map<String, List<String>> result = new HashMap<>();
        list.forEach(str -> result.put(str, Arrays.asList(str.split("_"))));
        

        ,输出

        {Opty_Act=[Opty, Act], MRkt_Cust=[MRkt, Cust], Indivdl_GNRC_Acct=[Indivdl, GNRC, Acct], Cust_Gnrc_Activity=[Cust, Gnrc, Activity]}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-04-25
          • 2014-09-27
          • 2019-04-08
          • 2021-11-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多