Home > Mobile >  How to display the name of cities sorted by population through streams?
How to display the name of cities sorted by population through streams?

Time:10-30

I study streams and solve various tasks with them. And I can’t cope with one, I have a map with cities and the amount of violence. I need to display only the name of the cities in descending order of the number of population.In fact, it should display the cities in this order Brest, Vitebsk,Minsk, Mogilev. No matter how I write, I can't, here's my code.

        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

CodePudding user response:

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.Entrys 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);

CodePudding user response:

You can sort by value using using Map.Entry.comparingByValue() and reverse it for descending orrder

cities.entrySet()
            .stream().sorted(Map.Entry.<String,Integer>comparingByValue().reversed())
            .forEach(System.out::println);

Output

Brest=4999234
Vitebsk=3999231
Minsk=1999234
Mogilev=1599234

If you specifically want to print key then use lambda to print it

forEach(e-> System.out.println(e.getKey()))

Use map and collect to collect keys into List

.map(Map.Entry::getKey)
.collect(Collectors.toList())
  • Related