<Object><Object> 使用 Java 8 将映射<对象、映射<对象、列表>>转换为集合



我有一个映射Map<LocalDate, Map<LocalDate, List<Request>>>,我想将其转换为Set<String>字符串是使用Java8

的请求类中的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()));

谢谢

首先,创建一个从映射值创建一个流和链条a map操作到地图值,然后用 flatMap连续弄平,最后将 map弄平到请求ID并收集设置实现。<<<<<<<<<<<<<<<</p>

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

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

最新更新