optional - Retrieve copy of an object from a java stream -
i want copy of object filtered stream.
by moment, made way.
foo foo = new foo(foolist.stream() .filter(f -> (f.getid().equals(anotherfooid))) .findany().orelse(new foo(anotherfooid)));
as can see, object have, among others contructors, 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 streams?
you call foo::new
after findany()
don't need instantiate 2 objects when don't find match:
foo foo = foolist.stream() .filter(f -> (f.getid().equals(anotherfooid))) .findany().map(foo::new).orelse(new foo(anotherfooid));