I have two classes: Country and City.
Country has the following attributes: code, name, capital, population, Continent and a list of type City.
City has code, name and population attributes.
I am trying to find the most populated city of each continent
I got the highest populated city of each country but how can I filter this by Continent which is a String, or can I re filter the list I got?
the highestPopulation get the highest populated city in each country and the continent list get the highest populated continent is there a way to mix those 2 to find the most populated city of each continent
public static void main(String[] args) {
List<Country> countries=new ArrayList<Country>();
System.out.println();
List<City> highestPopulation = countries.stream().map(x -> x.cities.stream().max(Comparator.comparingInt(City::getPopulation)).orElse(null)).toList();
for(City c: highestPopulation) {
System.out.println(c.code+" "+c.name+" "+c.population);
}
System.out.println();
Map<String, Optional<Country>> continent= countries.stream().collect(Collectors.groupingBy(Country::getContinent,Collectors.maxBy(Comparator.comparingInt(Country::getPopulation))));
for(Entry<String, Optional<Country>> c: con.entrySet()) {
System.out.println(c.getKey()+" "+c.getValue().get().name);
}