Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty Optionals from Stream using StreamEx

I'm searching for an elegant way to stream only non-empty Optional entries using the StreamEx library. Or the standard library, if it's possible.

Currently I'm using the following, rather verbose, approach:

List<Optional<String>> list = 
   Arrays.asList(Optional.of("A"), Optional.empty(), Optional.of("B"));

List<String> nonEmpty = 
   StreamEx.of(list).filter(Optional::isPresent).map(Optional::get).toList();

I'm essentially looking for something like StreamEx's nonNull method, but for Optional.

like image 588
Henrik Aasted Sørensen Avatar asked Apr 07 '26 14:04

Henrik Aasted Sørensen


2 Answers

Well this has been added, but only in java-9:

list.stream()
    .flatMap(Optional::stream)
    .collect(Collectors.toList());

There is a back-port from Stuart Marks here

like image 84
Eugene Avatar answered Apr 11 '26 18:04

Eugene


A bit of research into the StreamEx issue backlog revealed issue 49, which provides a shorter approach and contains a discussion on the topic:

List<String> nonEmpty = StreamEx.of(list).flatMap(StreamEx::of).toList();

Shorter, although whether it's more readable is up for discussion.

like image 28
Henrik Aasted Sørensen Avatar answered Apr 11 '26 19:04

Henrik Aasted Sørensen