How to use multiple streams and in Java 8 with lambda expressions Map function
•
Java
I have a list County, which only contains the unique county name, and a list txcrarray, which contains the city name, county name and population of the city
I need to use Java 8 with lambda expression and streams to get the maximum city name of each county from TXC array
This is my code 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'm trying to find a way out Add another after max() Map statement to get the names of cities with the maximum population, but my new lambda expression does not exist in the txcrarray stream. It only recognizes it as int type and texascitiesclass type This is what I want 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 did wrong?
Solution
You don't need the county list at all Simply stream txcrarray 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();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码