Concatenate Optional Lists

后端 未结 3 1386
不思量自难忘°
不思量自难忘° 2021-01-14 10:49

I have three Optional> which have to be combined and returned. I tried to use Optional.map() and flatmap() but was not successful.

         


        
3条回答
  •  一整个雨季
    2021-01-14 11:10

    Something like :

    return Optional.of(Stream.of(entity1.orElse(new ArrayList<>()), entity2.orElse(new ArrayList<>()), entity3.orElse(new ArrayList<>()))
                .flatMap(List::stream)
                .collect(Collectors.toList()));
    

    or rather more readable as :

    return Optional.of(Stream.of(entity1, entity2, entity3)
            .filter(Optional::isPresent)
            .map(Optional::get)
            .flatMap(List::stream)
            .collect(Collectors.toList()));
    

提交回复
热议问题