Search code examples
javajava-streamcompletable-future

Filtering a stream of CompletableFuture<SomeObject> on some attribute of SomeObject


I have a Stream of CompletableFuture of SomeObject and I'm trying to filter this on some attribute of SomeObject and I can't seem to find a satisfying way to filter this.

public class SomeObject {
    private String someAttribute;

    public String getSomeAttribute() {
        return someAttribute;
    } 
}

I tried this, but I'm wondering if there is a non-blocking way ?

  public List<CompletableFuture<SomeObject>> filterStream(Stream<CompletableFuture<SomeObject>> stream) {
        return stream.filter(futureSomeObject -> {
            try {
                return futureSomeObject.get().getSomeAttribute().equals("SOMETHING");
            } catch (InterruptedException | ExecutionException e) {
                return false;
            }
        }).toList();
  }

I also thought of something like this, but I'll need to change the return signature :

stream.map(CompletableFuture::join).filter(object -> object.getSomeAttribute().equals("SOMETHING")).toList();

Solution

  • As pointed out in the comments it seems this is the way I was looking for:

    public List<CompletableFuture<SomeObject>> filterStream(Stream<CompletableFuture<SomeObject>> stream) {
       return stream.filter(f -> f.join().getSomeAttribute().equals("SOMETHING")).toList()
    }