转换Map <object,map <object,list <object>&gt;&gt;使用Java 8设置<object>

时间:2018-03-25 13:32:19

标签: java java-8 java-stream

我有一张地图Map<LocalDate, Map<LocalDate, List<Request>>>,我希望将其转换为Set<String> 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选项(流,地图,收集......)实现这一目标。

我正在尝试这个,正在编译错误

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

由于

2 个答案:

答案 0 :(得分:4)

首先,从地图值创建一个流,并将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());

答案 1 :(得分:0)

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());