Oct*_*cia 5 java collections lambda java-8 java-stream
我有一个List counties仅包含唯一县名的,List txcArray其中包含该城市的城市名称,县名和人口.
我需要txcArray使用带有lambda表达式和Streams的Java 8 来获取每个县的最大城市名称.
这是我到目前为止的代码:
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());
Run Code Online (Sandbox Code Playgroud)
我试图在之后添加另一个.map语句.max()来获取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());
Run Code Online (Sandbox Code Playgroud)
有人能告诉我我做错了什么吗?
您完全不需要counties列表.只是txcArray按县分组和分组:
Collection<String> largestCityNames = txcArray.stream()
.collect(Collectors.groupingBy(
City::getCounty,
Collectors.collectingAndThen(
Collectors.maxBy(City::getPopulation),
o -> o.get().getName())))
.values();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3174 次 |
| 最近记录: |