[英]In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?
[英]How do I transform a Map<K,V1> to another Map<K,V2> using a map of functions in Java 8?
我想使用Java 8中的函數映射將Map<String, Integer>
為另一個Map<String, Long>
,在兩個映射中將數據與按鍵匹配的函數進行匹配。 您可以假設兩個地圖都具有相同的鍵。
我嘗試了以下方法:
Map<String, Integer> inputData = new HashMap<>();
inputData.put("A",8);
inputData.put("B",7);
inputData.put("C",6);
Map<String, Function<Integer, Long>> transformers = new HashMap<>();
transformers.put("A", x -> x*2L);
transformers.put("B", x -> x+3L);
transformers.put("C", x -> x+11L);
Map<String, Long> mappedData = inputData.entrySet().stream()
.map(entry -> new AbstractMap.SimpleEntry<>(
entry.getKey(),
transformers.get(entry.getKey()).apply(entry.getValue())))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
預期結果:{A = 16,B = 10,C = 17}。
在Java Streams API中是否有更簡單的方法表達“ 將變換器的映射應用於按鍵匹配的inputData映射 ”?
您可以直接在收集器中進行轉換:
Map<String, Long> mappedData = inputData.entrySet().stream()
.collect(toMap(Map.Entry::getKey,
entry -> transformers.get(entry.getKey()).apply(entry.getValue())));
這種解決方案更短,不會產生中間對象。
如果您的inputData
具有相同的值類型( Map<String, Long>
),您可以就地執行轉換:
inputData.replaceAll((key, value) -> transformers.get(key).apply(value));
您也可以從transformers
地圖本身開始,看起來更容易:
Map<String, Long> collect = transformers.entrySet().stream()
.collect(toMap(Map.Entry::getKey,
e -> e.getValue().apply(inputData.get(e.getKey()))));
如果一條額外的線條不打擾你,試試吧
Map<String, Long> result = new HashMap<>(); // this line
inputData.forEach((k, v) -> result.put(k, transformers.get(k).apply(v));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.