如何使用Collectors的groupingBy方法将频率映射到新对象?

huangapple go评论77阅读模式
英文:

How to map frequencies to a new object with Collectors groupingBy?

问题

获取类对象的描述频率:

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

我使用了Collectors的groupingBy + counting函数

```java
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<String, Long>。有没有简单的方法来实现这个?

英文:

To get the description frequencies of class objects:

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

I use Collectors groupingBy + counting functions:

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

But I want to return the result as a new object of the class

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

instead of Map&lt;String, Long&gt;. What is a simple way to do it?

答案1

得分: 2

可以获取映射的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())))));
英文:

You can get entrySet of map and transform into Frequency class and collect as List.

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

Or using Collectors.collectingAndThen

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

huangapple
  • 本文由 发表于 2020年9月18日 17:02:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63952629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定