With Java 8 you can do:
Map<String, String> byNameMap = new HashMap<>();
people.forEach((k, v) -> byNameMap.put(k, v.getName());
Though you'd be better off using Guava's Maps.transformValues, which wraps the original Map
and does the conversion when you do the get
, meaning you only pay the conversion cost when you actually consume the value.
Using Guava would look like this:
Map<String, String> byNameMap = Maps.transformValues(people, Person::getName);
EDIT:
Following @Eelco's comment (and for completeness), the conversion to a map is better done with Collectors.toMap like this:
Map<String, String> byNameMap = people.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> entry.getValue().getName());