给定一个包含
在 Java 8 之前,我会使用
String, Person
的 Map
,其中 Person
有一个 String getName()
方法,我该如何将 Map<String, Person>
转换为 Map<String, String>
,其中的 String
是通过调用 Person::getName()
获得的?在 Java 8 之前,我会使用
Map<String, String> byNameMap = new HashMap<>();
for (Map.Entry<String, Person> person : people.entrySet()) {
byNameMap.put(person.getKey(), person.getValue().getName());
}
但我希望使用流和lambda表达式来完成它。
我无法想象如何以函数式风格实现:Map / HashMap没有实现Stream
。
people.entrySet()
返回一个 Set<Entry<String, Person>>
,我可以在其上进行流处理,但是如何向目标映射添加一个新的 Entry<String, String>
?
Collectors.toMap
确实是这样做的方法(当我回答这个问题时,我才刚开始接触Java 8)。 - Nick HoltMap<...> newMap = map.mapValues(mapFunction)
... - vinntec