gpt4 book ai didi

java-8 - 在 Java8 中使用 groupingBy 和 summingInt 扩展流的输出

转载 作者:行者123 更新时间:2023-12-01 15:22:12 26 4
gpt4 key购买 nike

我有一个主题:

@Entity
public class Topic {
@Id
private int id;
private LocalDate date;
private String name;
private int points;
@JoinColumn(name = "user_id", nullable = false)
private User user;
}

我通过 spring data jpa 方法获取给定日期的主题列表:

List topics = topicRepository.findByDateBetween(begin, end);输出有例如:

Topic(id=1, date="2018-01-01", name="Java examples", User(...), 12)
Topic(id=2, date="2018-02-02", name="Java examples", User(...), 34)
Topic(id=3, date="2018-02-02", name="Java examples", User(...), 56)
Topic(id=4, date="2018-03-03", name="Java examples", User(...), 78)
Topic(id=5, date="2018-03-03", name="Java examples", User(...), 90)

我试图实现的是将我的结果输出过滤为(如果日期 && 用户是相同的添加点)

Topic(id=1, date="2018-01-01", name="Java examples", User(...), 12)
Topic(id=2, date="2018-02-02", name="Java examples", User(...), 90)
Topic(id=4, date="2018-03-03", name="Java examples", User(...), 168)

我的实际解决方案返回以日期为键、以求和点为值的 map ,但我需要在输出中提供更多数据,如用户或名称。

return topics.stream()
.collect(Collectors.groupingBy(Topic::getDate,
Collectors.summingInt(Topic::getPoints)));

也许有另一种方法可以代替 map return 为这种情况创建 dto?例如

@Data
public class ResultDto {
private LocalDate date;
private String name;
private int points;
private User user;
}

最佳答案

按字段子集分组的一种简单方法是使用带有自定义 ComparatorTreeMap。假设你要定义

Comparator<Topic> byDateAndUser = Comparator.comparing(Topic::getDate)
.thenComparing(t -> t.getUser().getUserId());

Map<Topic,...> map = new TreeMap<>(byDateAndUser);

生成的 map 将使用提供的比较器而不是 equals 来确定相等性,因此会将具有相同日期和用户的所有主题视为相同。

TreeMap 的这一特性允许您计算主题到总分的映射,并且它将只包含一个日期/用户组合的条目:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingInt;

Comparator<Topic> byDateAndUser = Comparator.comparing(Topic::getDate)
.thenComparing(t -> t.getUser().getUserId());

Map<Topic, Integer> pointTotals = topics.stream()
.collect(groupingBy(
topic -> topic,
() -> new TreeMap<>(byDateAndUser),
summingInt(Topic::getPoints)
));

关于java-8 - 在 Java8 中使用 groupingBy 和 summingInt 扩展流的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52260488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com