How to use multiple streams and .map functions in java 8 with lambda expressions

Octavio garcia :

I have a List counties which contains unique county names only, and a List txcArray which contains a city name, county name and population for that city.

I need to get the largest city name of each county from txcArray using only Java 8 with lambda expressions and Streams.

Here is the code I have so far:

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());

I am trying to add another .map statement after .max() to get the name of the City with the largest population but my new lambda expression does not exists from the stream of txcArray it only recognizes it as an int type and a texasCitiesClass type. Here is what I am trying to do.

 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());

Can someone tell me what I am doing wrong?

shmosel :

You don't need the counties list altogether. Just stream txcArray and group by county:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474172&siteId=1