英文:
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<String, Long> frequencyMap = rawTags.stream().map(Tag::getDescription).collect(Collectors.groupingBy(e -> 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<String, Long>
. 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 -> e, Collectors.counting()))
.entrySet()
.stream()
.map(e -> new Frequency(e.getKey(), e.getValue()))
.collect(Collectors.toList());
Or using 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())))));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论