是否可以对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
});
});
}
这工作得很好,但似乎有点麻烦,尤其是流进一个地图,然后立即进入集映射的流。
有没有办法将流中的对象分组,但继续流式传输?
简单的答案是*不*;但可能你可以准确解释你想要达到的目标(输入和输出),我们可以帮助解决这个问题? – Eugene
@Eugene谢谢。这个问题恰恰包含了我想达到的目标,或多或少。我有dateMap的工作,我需要输出行到按日期,然后姓氏,按日期或姓氏排序的报告。 – lucasvw
在你的问题中没有任何明显的。我可以推论的是,你想按日期订购人员,然后按姓氏。这种排序是否足够,还是你真的需要将它们分组? – VGR