2015-09-02 95 views
2

假設我們有以下功能:的Java 8流 - 映射將

public Map<String, List<String>> mapListIt(List<Map<String, String>> input) { 
    Map<String, List<String>> results = new HashMap<>(); 
    List<String> things = Arrays.asList("foo", "bar", "baz"); 

    for (String thing : things) { 
     results.put(thing, input.stream() 
           .map(element -> element.get("id")) 
           .collect(Collectors.toList())); 
    } 

    return results; 
} 

有沒有一些方法,我可以通過結合"id"Map::get方法參考打掃一下嗎?

是否有更多的stream-y方法來編寫此功能?

+2

我不明白這個功能的目的。它不能編譯,因爲你沒有關閉result.put(如果我添加一個,它會創建一個映射,其中映射中的每個元素映射到爲每個項目創建的相同列表。 – WillShackleford

+1

可能'element - > element .get(thing)'was intended。 –

+0

從列表中的每個映射中,我想要使用''id''鍵來獲取字段的值,它是按照預期寫入的 –

回答

4

據我可以告訴你想要的是這個函數返回一個從定義的字符串列表到輸入地圖列表中具有關鍵字「id」的所有元素列表的映射。那是對的嗎?

如果因此它可以顯著簡化爲所有密鑰的值將是相同的:

public Map<String, List<String>> weirdMapFunction(List<Map<String, String>> inputMaps) { 
    List<String> ids = inputMaps.stream() 
     .map(m -> m.get("id")).collect(Collectors.toList()); 
    return Stream.of("foo", "bar", "baz") 
     .collect(Collectors.toMap(Function.identity(), s -> ids)); 
} 

如果您希望使用的方法引用(這是我對「結合」你的問題的解釋)那麼你將需要一個單獨的方法來引用:

private String getId(Map<String, String> map) { 
    return map.get("id"); 
} 

public Map<String, List<String>> weirdMapFunction(List<Map<String, String>> inputMaps) { 
    List<String> ids = inputMaps.stream() 
     .map(this::getId).collect(Collectors.toList()); 
    return Stream.of("foo", "bar", "baz") 
     .collect(Collectors.toMap(Function.identity(), s -> ids)); 
} 

不過,我猜你打算在列表中的鑰匙使用的項目(而不是「ID」)在這種情況下:

public Map<String, List<String>> weirdMapFunction(List<Map<String, String>> inputMaps) { 
    return Stream.of("foo", "bar", "baz") 
     .collect(Collectors.toMap(Function.identity(), s -> inputMaps.stream() 
      .map(m -> m.get(s)).collect(Collectors.toList()))); 
} 
+0

在第一種情況下,您是正確的!我在找,謝謝! –