假设我们有以下函数:
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"
绑定(bind)到 Map::get
方法引用来清理这个问题吗?
是否有更流式的方式来编写此功能?
最佳答案
据我所知,您的意图是,该函数从定义的字符串列表返回一个映射,该映射从输入映射列表中键为“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));
}
如果您希望使用方法引用(这是我对“绑定(bind)”问题的解释),那么您将需要一个单独的方法来引用:
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())));
}
关于Java 8 Streams — 映射映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32364867/