1

I have class country:

class Country {
private String code;
private String name;
}

I need to do from list of Countries to Map with code and name. I tried to

Map<String, String> countryNames = countries.stream()
            .collect(Collectors.groupingBy(Country::getCode, Country::getName));

But it is not right. How to collect correct?

Krazim00da
  • 307
  • 1
  • 5
  • 14

1 Answers1

3

I assume you want code as the key and name as the value. In that case, you need to use Collectors.mapping as the downstream collector to Collectors.groupingBy. Like this:

Map<String, List<String>> countryNames = countries.stream()
        .collect(Collectors.groupingBy(Country::getCode, 
            Collectors.mapping(Country::getName, Collectors.toList())));

Note that this will return the values as a list of strings, as the names are grouped in a list (by Collectors.toList()) if there are multiple countries with the same code.

If you know that each code only appears once in the list, you can use Collectors.toMap instead.

Map<String, String> countryNames = countries.stream()
        .collect(Collectors.toMap(Country::getCode, Country::getName));
marstran
  • 26,413
  • 5
  • 61
  • 67