gpt4 book ai didi

java - 如何在带有 lambda 表达式的 Java 8 中使用多个流和 .map 函数

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:53 27 4
gpt4 key购买 nike

我有一个 List counties,它只包含唯一的县名,还有一个 List txcArray,它包含城市名称、县名和该城市的人口。

我需要仅使用带有 lambda 表达式和 Stream 的 Java 8 从 txcArray 获取每个县的最大城市名称。

这是我目前的代码:

List<String> largest_city_name = 
counties.stream()
.map(a -> txcArray.stream()
.filter(b -> b.getCounty().equals(a))
.mapToInt(c -> c.getPopulation())
.max())
.collect( Collectors.toList());

我试图在 .max() 之后添加另一个 .map 语句以获取人口最多的 City 的名称,但我的新 lambda 表达式不存在从 txcArray 的流中,它只将其识别为 int 类型和 texasCitiesClass 类型。这就是我想要做的。

 List<String> largest_city_name = 
counties.stream()
.map(a -> txcArray.stream()
.filter( b -> b.getCounty().equals(a))
.mapToInt(c->c.getPopulation())
.max()
.map(d->d.getName()))
.collect( Collectors.toList());

谁能告诉我我做错了什么?

最佳答案

您完全不需要 counties 列表。只需流式传输 txcArray 并按县分组:

Collection<String> largestCityNames = txcArray.stream()
.collect(Collectors.groupingBy(
City::getCounty,
Collectors.collectingAndThen(
Collectors.maxBy(City::getPopulation),
o -> o.get().getName())))
.values();

关于java - 如何在带有 lambda 表达式的 Java 8 中使用多个流和 .map 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46678548/

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