我有一个List县,它只包含唯一的县名,还有一个List txcArray,其中包含该城市的城市名称,县名和人口.
我需要使用带有lambda表达式和Streams的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());
有人能告诉我我做错了什么吗?
解决方法
您根本不需要县名单.只需流txcArray并按县分组:
Collection<String> largestCityNames = txcArray.stream() .collect(Collectors.groupingBy( City::getCounty,Collectors.collectingAndThen( Collectors.maxBy(City::getPopulation),o -> o.get().getName()))) .values();