Java 8 Streams — 映射映射

标签 java java-8 java-stream

假设我们有以下函数:

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/

相关文章:

java - "Preconditions"和日志记录参数不需要评估

java - Field#getGenericType() 抛出 java.lang.TypeNotPresentException

java - java.time中,加一个月的结果是怎么计算的?

Java Stream - NullPointExeption when filter list

java - 如何将 "nested for each"转换为 Java 8 Lambda/Stream 构造?

java - 是否可以使用 Java 8 Streams 过滤器访问列表的索引?

java - VBA 中的备忘录实现

lambda - Java8 lambda : sort a stream in reverse order?

Java 8 LocalDateTime 今天在特定时间

java - 如何在Spring Controller 中从一个表单保存多个相同的实体?