給定一個Map<String, Person>
其中Person有一個String getName()
(etc)方法,如何將Map<String, Person>
變成Map<String, String>
,String
從Person::getName()
獲得?使用流,我如何映射HashMap中的值?
前的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>
添加到目標地圖?
我接受這個,因爲它非常整潔,並且沒有令人厭煩的循環。 Guave解決方案特別整潔。謝謝 –
@DavidKerr請注意,第一個代碼是不可並行化的,因爲HashMap不是線程安全的,與使用收集器/ toMap來分割作業(如果該流並行)相反。番石榴的版本也是不可並行的。但如果這不是一個問題,那麼一定要用這個版本。 – assylias
第一個解決方案不起作用。另一個使用toMap收集器的答案是。 – Eelco