Given a Map<String, Person>
where Person has a String getName()
(etc) method on it, how can I turn the Map<String, Person>
into a Map<String, String>
where the String
is obtained from calling Person::getName()
?
Pre-Java 8 I'd use
Map<String, String> byNameMap = new HashMap<>();
for (Map.Entry<String, Person> person : people.entrySet()) {
byNameMap.put(person.getKey(), person.getValue().getName());
}
but I'd like to do it using streams and lambdas.
I can't see how to do this in a functional style: Map/HashMap don't implement Stream
.
people.entrySet()
returns a Set<Entry<String, Person>>
which I can stream over, but how can I add a new Entry<String, String>
to the destination map?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…