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

我有一个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();

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...