【问题标题】:How to get unique values with frequency from List<String[]> in Java?如何从 Java 中的 List<String[]> 获取具有频率的唯一值?
【发布时间】:2019-10-10 23:21:31
【问题描述】:

我想从List&lt;String[]&gt; 中获取唯一值并将它们存储在一个新列表中(或HashMap&lt;String, Integer&gt;,其中String 是唯一值,Integer 是它在List&lt;String[]&gt; 中的出现次数。如何我可以提取唯一值吗?

【问题讨论】:

    标签: java arrays string list


    【解决方案1】:

    您可以使用Collectors.groupingBy

    Map<String, Long> map = abc.stream()
                               .flatMap(Arrays::stream)
                               .collect(Collectors.groupingBy(Function.identity(),
                                           Collectors.counting()));
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Java 8 或更高版本,这很容易。 (使用其他答案稍作修正)

      List<String[]> abc = new ArrayList<>();
      String[] string1 = {"123", "567"};
      String[] string2 = {"123", "456"};
      abc.add(string1);
      abc.add(string2);
      
      List<String> newList = abc.stream()
              .flatMap(Arrays::stream)
              .distinct()
              .collect(Collectors.toList());
      
      Map<String, Long> hashMap = abc.stream()
                  .flatMap(Arrays::stream)
                  .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
      

      【讨论】:

        猜你喜欢
        • 2020-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多