I study streams and solve various tasks with them. And I can’t cope with one. I have a map with cities and the population. I need to display only the name of the cities in descending order of the population. No matter how I write, I can't.
In the following example, it should display the cities in this order Brest, Vitebsk, Minsk, Mogilev.
Map<String,Integer> cities = new HashMap<>();
cities.put("Minsk",1999234);
cities.put("Mogilev",1599234);
cities.put("Vitebsk",3999231);
cities.put("Brest",4999234);
List<Integer> collect =cities.entrySet().stream()
.map(o->o.getValue())
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
So far, I was able to sort by population, but I don’t understand how to display the name of the cities sorted further.
Instead of mapping to the value first and then sorting, sort first, and then you can map to the name or do anything else with the stream of cities
You can sort Map.Entry
s by value using the comparingByValue
comparator:
var cityNames = cities.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.map(Map.Entry::getKey)
.toList();
System.out.println(cityNames);
Note that it might be better if you create a record/class to model the cities, instead of using a Map
.
record City(String name, int population) {}
In which case the sorting code would become:
List<City> cities = List.of(
new City("Minsk",1999234),
new City("Mogilev",1599234),
new City("Vitebsk",3999231),
new City("Brest",4999234)
);
var cityNames = cities.stream()
.sorted(Comparator.comparingInt(City::population).reversed())
.map(City::name)
.toList();
System.out.println(cityNames);