【问题标题】:Java ArrayList same string grouping and get most frequent String [duplicate]Java ArrayList相同的字符串分组并获得最频繁的字符串[重复]
【发布时间】:2021-01-30 03:45:00
【问题描述】:

我有一个包含字符串的列表并将相同的字符串分组。

List<String> allTypes = new ArrayList<String>();

Map<String, Long> count = allTypes.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

然后我得到最频繁字符串的计数

Long max = Collections.max(count.values());

现在我不只想要我想要的最频繁字符串的计数 也关联字符串。 List 中随机填充了来自其他 List 的字符串。

【问题讨论】:

    标签: java string list java-stream


    【解决方案1】:

    我认为您希望:

    Optional<Map.Entry<String, Long>> maxEntryByValue = count.entrySet()
            .stream()
            .max(Comparator.comparing(Map.Entry::getValue));
    

    或者如果你想要它没有Optional,你可以使用:

    Map.Entry<String, Long> maxEntryByValue = count.entrySet()
            .stream()
            .max(Comparator.comparing(Map.Entry::getValue))
            .orElse(null); // or any default value, or you can use orElseThrow(..)
    

    【讨论】:

    • max 调用可以更简洁地写成max(Map.Entry::comparingByValue)
    • 您可能应该提到,如果 2 个字符串(键)具有相同的计数,则只会返回一个条目。如果要求是返回多个地图条目,如果最大值不是唯一值,我想你可以使用List&lt;Entry&lt;String, Long&gt;&gt; maxEntries = count.entrySet().stream().filter(x -&gt; x.getValue().equals(Collections.max(count.values()))).collect(Collectors.toList()); 之类的东西来做到这一点(可能不是很有效,只是我的第一个想法)
    • @VGR 我尝试了你的解决方案,但它无法解析方法'comparingByValue'
    • @OHGODSPIDERS 是的,我同意,如果 OP 等待多个值,那么他/她应该采用另一种方法。
    【解决方案2】:

    您可以遍历条目,如果 value 与您的 targetValue 匹配,则将该键存储在 Set&lt;K&gt; keys 中。这将包含具有特定 targetValue

    的所有键
        for (Map.Entry<String, Object> entry : map.entrySet()) {
          String key = entry.getKey();
          Object value = entry.getValue();
          if (value.equals(targetValue)) {
            keys.add(entry.getKey());//add the keys to the set<K> keys
          }
        }
        return keys; //all the keys having the same targetValue will be in this set
    

    【讨论】:

      猜你喜欢
      • 2015-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多