gpt4 book ai didi

java - 是否可以在不关闭流的情况下对元素进行分组?

转载 作者:行者123 更新时间:2023-11-30 06:39:04 25 4
gpt4 key购买 nike

是否可以将元素分组到 Stream 中,然后继续流式传输,而不必从返回映射的 EntrySet 创建新流?

例如,我可以这样做:

public static void main(String[] args) {
// map of access date to list of users
// Person is a POJO with first name, last name, etc.
Map<Date, List<Person>> dateMap = new HashMap<>();
// ...
// output, sorted by access date, then person last name
dateMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
Date date = e.getKey();
// group persons by last name and sort
// this part seems clunky
e.getValue().stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()))
.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e2 -> {
// pool agent id is the key
String lastName = e2.getKey();
Set<Person> personSet = e2.getValue();
float avgAge = calculateAverageAge(personSet);
int numPersons = personSet.size();
// write out row with date, lastName, avgAge, numPersons
});
});
}

这工作得很好,但似乎有点笨拙,尤其是流式传输到 map ,然后立即流式传输到该 map 的条目集。

有没有办法将流中的对象分组,但继续流式传输?

最佳答案

您可以使用 Map.forEach、下游收集器、TreeMap 和 IntSummaryStatistics 来缩短代码。

通过分组到 TreeMap(而不是将其留给 groupingBy 收集器),您可以自动对名称进行排序。您无需立即获取分组 map ,而是添加一个 summarizingInt 收集器,将同名人员列表转换为他们年龄的 IntSummaryStatistics

public static void main(String[] args) {
Map<Date, List<Person>> dateMap = new HashMap<>();
dateMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
Date date = e.getKey();

e.getValue().stream()
.collect(Collectors.groupingBy(Person::getLastName,
TreeMap::new,
Collectors.summarizingInt(Person::getAge)))
.forEach((name, stats) -> System.out.println(date +" "+
lastName +" "+
stats.getAverage() +" "+
stats.getCount()));
});
}

如果您可以控制初始 map 的类型,您也可以在那里使用 TreeMap,并进一步缩短它:

public static void main(String[] args) {
Map<Date, List<Person>> dateMap = new TreeMap<>();
dateMap.forEach((date, persons -> { ...

关于java - 是否可以在不关闭流的情况下对元素进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44706927/

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