【问题标题】:How to map frequencies to a new object with Collectors groupingBy?如何使用 Collectors groupingBy 将频率映射到新对象?
【发布时间】:2021-01-05 05:00:16
【问题描述】:

获取类对象的描述频率:

public class Tag {  
    private int excerptID;
    private String description;
}

我使用 Collectors groupingBy + 计数函数:

Map<String, Long> frequencyMap = rawTags.stream().map(Tag::getDescription).collect(Collectors.groupingBy(e -> e, Collectors.counting()));

但我想将结果作为类的新对象返回

 public class Frequency {
    private String Description;
    private Long frequency;
    }

而不是Map&lt;String, Long&gt;。有什么简单的方法吗?

【问题讨论】:

    标签: java collectors groupingby


    【解决方案1】:

    你可以得到map的entrySet并转换成Frequency类并收集为List。

    rawTags.stream()
           .map(Tag::getDescription)
           .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
           .entrySet()
           .stream()
           .map(e -> new Frequency(e.getKey(), e.getValue()))
           .collect(Collectors.toList());
    

    或使用Collectors.collectingAndThen

    rawTags.stream()
        .map(Tag::getDescription)
        .collect(Collectors.groupingBy(e -> e,
                  Collectors.collectingAndThen(Collectors.toList(),
                                    e -> new Frequency(e.get(0), Long.valueOf(e.size())))));
    

    【讨论】:

    • 第二种方法Collectors.collectingAndThen 效果很好,但在第一种方法中,最后一个map 加下划线并抛出消息The method map((&lt;no type&gt; e) -&gt; {}) is undefined for the type Set&lt;Map.Entry&lt;String,Long&gt;&gt;
    • @krenkz 你能再检查一下吗?这个对我有用。更新答案时,我忘了在entrySet() 之后加上.stream(),也许这就是问题所在。
    • 对不起,我的错...我用的是没有stream()的原版,效果很好,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多