gpt4 book ai didi

java - 将函数应用于按流分组的嵌套列表

转载 作者:行者123 更新时间:2023-11-30 05:28:54 25 4
gpt4 key购买 nike

有以下类的对象列表:

class A {
String firstName;
String lastName;
//.....
}

还有一个接受三个参数的方法:

List<B> someMethod(String firstName, String lastName, List<A> l);

我想根据 firstNamelastName 对此列表进行分组,然后将此方法应用于具有 firstName 的项目列表中的项目> 和姓氏

我尝试了以下方法:

Map<String, Map<String, List<B>>> groupedItems = l.stream()
.collect(groupingBy(A::getFirstName, groupingBy(A::getLastName)));

List<B> result = groupedItems.keySet().stream()
.map(firstName -> groupedItems.get(firstName).keySet().stream()
.map(lastName -> someMethod(firstName, lastName, groupedItems.get(firstName).get(lastName))
.collect(Collectors.toList()))
.flatMap(Collection::stream)
.collect(Collectors::toList);

有没有一种方法可以一次性完成此操作,而不是像现在这样?

最佳答案

您可以使用collectingAndThen来完成此操作,但在我看来,这的可读性要差得多。

List<B> result = l.stream().collect(Collectors.collectingAndThen(
groupingBy(A::getFirstName, groupingBy(A::getLastName)),
groupedItems -> groupedItems.keySet().stream()
.flatMap(firstName ->
groupedItems.get(firstName)
.keySet()
.stream()
.map(lastName ->
someMethod(
firstName,
lastName,
groupedItems.get(firstName).get(lastName)
)
)
)
.flatMap(Collection::stream)
.collect(toList())));

关于java - 将函数应用于按流分组的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57967884/

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