2015-09-02 94 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

在第一种情况下,您是正确的!我在找,谢谢! –