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