【问题标题】:Converting Map<Object,Map<Object,List<Object>>> to Set<Object> using Java 8使用 Java 8 将 Map<Object,Map<Object,List<Object>>> 转换为 Set<Object>
【发布时间】:2018-03-25 13:32:18
【问题描述】:

我有一张地图 Map&lt;LocalDate, Map&lt;LocalDate, List&lt;Request&gt;&gt;&gt;,我想将其转换为 Set&lt;String&gt;String 是使用 Java8 的 Request 类中的 id

请求类

class Request{
  private String id;

  public void setId(String id){
   this.id =id;
 }

  public String getId(){
   return this.id;
 }

}

我知道这样做的传统方式,但希望使用 Java 8 选项(Stream、Map、Collect..)来实现这一点

我在尝试这个,得到编译错误

Set<String> values = map.values().stream()
              .map(dateMap -> dateMap.values().stream()
                    .map(request -> request.stream()
                          .map(Request::getId)).flatMap(Set::stream).collect(Collectors.toSet()));

谢谢

【问题讨论】:

  • 向我们展示您的尝试,我们不是代码交付服务
  • @LukeGarrigan,我错过了,现在添加。

标签: java java-8 java-stream


【解决方案1】:

首先,从映射值创建一个流并将map 操作链接到映射值,然后用flatMap 连续展平,最后将map 展平到请求ID 并收集到一个集合实现。

Set<String> resultSet = 
             map.values()
                .stream()
                .map(Map::values)
                .flatMap(Collection::stream)
                .flatMap(Collection::stream)
                .map(Request::getId)
                .collect(Collectors.toSet());

【讨论】:

    【解决方案2】:
    map.values().stream()
        .map(Map::values) //now you have a stream of Set of List
        .flatMap(Set::stream) //now you have a stream of List
        .flatMap(List::stream) //now you merged all the streams and have a stream of Object
        .map(Request.class::cast) //you now casted all the objects, if needed (your title and post don't match)
        .map(Request::getId) //request becomes String
        .collect(Collectors.toSet());
    

    【讨论】:

    • 关闭但不完全。你能看到如何解决你的问题吗?另请注意,注释是//,而不是`\\`。另外,我认为您应该收集到集合实现而不是列表实现。
    • @Aominè 我认为我的回答有几个错误。实际上我不擅长通过智能手机编写代码?我已经看到你的答案,我会支持你的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    相关资源
    最近更新 更多