Retrieve copy of an object from a java stream

I want to get a copy of an object from a filtered stream.

By the moment, I made this way.

Foo foo = new Foo(fooList.stream()
                .filter(f -> (f.getId().equals(anotherFooId)))
                .findAny().orElse(new Foo(anotherFooId)));

As can see, this object have, among others contructors, a clone constructor.

class Foo {    
   private String id;
   Foo(String id) {
      this.id = id;
   }
   Foo(Foo originalFoo) {
      this.id = originalFoo.getId();
   }
}

My question is, There's no more elegant way to do this with streams?

Upvotes: 3

Views: 3021

Answers (2)

Anderson Vieira
Anderson Vieira

Reputation: 9059

You could call Foo::new after findAny() so you don't need to instantiate two objects when you don't find a match:

Foo foo = fooList.stream()
                 .filter(f -> (f.getId().equals(anotherFooId)))
                 .findAny().map(Foo::new).orElse(new Foo(anotherFooId));

Upvotes: 4

Blazo
Blazo

Reputation: 194

Foo foo = new Foo(fooList.stream()
            .filter(f -> (f.getId().equals(anotherFooId)))
            .findAny().get());

Upvotes: 0

Related Questions