Concatenate Optional Lists

后端 未结 3 1425
不思量自难忘°
不思量自难忘° 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:01

    I suggest that you don’t want to return an Optional from your method. In case there are no records in any of the three entity lists, the caller would prefer just to have an empty list.

    public List getRecords() {
        return Stream.of("1", "2", "3")
                .map(repo::findAllByStatus)
                .flatMap(el -> el.map(List::stream).orElse(Stream.empty()))
                .collect(Collectors.toList());
    }
    

    A couple of the other answers use isPresent and get. They are low-level, and we don’t need them here.

    We don’t absolutely need the stream operation, though. Here’s a possibility without it:

    public List getRecords() {
        List concatenation = new ArrayList<>();
        repo.findAllByStatus("1").ifPresent(concatenation::addAll);
        repo.findAllByStatus("2").ifPresent(concatenation::addAll);
        repo.findAllByStatus("3").ifPresent(concatenation::addAll);
        return concatenation;
    }
    

提交回复
热议问题