鉴于我们有以下职能:
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方法引用来清除这个问题吗?
是否有更多的流-y方式来编写此功能?
发布于 2015-09-03 01:50:36
据我所知,您要知道的是,此函数将从定义的字符串列表返回一个映射到输入映射列表中具有键"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())));
}https://stackoverflow.com/questions/32364867
复制相似问题