首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Java 8流-映射映射

Java 8流-映射映射
EN

Stack Overflow用户
提问于 2015-09-02 23:43:01
回答 1查看 1.6K关注 0票数 2

鉴于我们有以下职能:

代码语言:javascript
运行
复制
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方式来编写此功能?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-03 01:50:36

据我所知,您要知道的是,此函数将从定义的字符串列表返回一个映射到输入映射列表中具有键"id“的所有元素列表。对吗?

如果是这样,则可以大大简化,因为所有键的值都是相同的:

代码语言:javascript
运行
复制
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));
}

如果您希望使用方法引用(这是我对您关于“绑定”的问题的解释),那么您将需要一个单独的方法来引用:

代码语言:javascript
运行
复制
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"),在这种情况下:

代码语言:javascript
运行
复制
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())));
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32364867

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档