java - Cannot make filter->forEach->collect in one stream? -
i want achieve this:
items.stream() .filter(s-> s.contains("b")) .foreach(s-> s.setstate("ok")) .collect(collectors.tolist()); filter, change property filtered result, collect result list. however, debugger says:
cannot invoke
collect(collectors.tolist())on primitive typevoid.
do need 2 streams that?
the foreach designed terminal operation , yes - can't after call it.
the idiomatic way apply transformation first , collect() desired data structure.
the transformation can performed using map designed non-mutating operations.
if performing non-mutating operation:
items.stream() .filter(s -> s.contains("b")) .map(s -> s.withstate("ok")) .collect(collectors.tolist()); where withstate method returns copy of original object including provided change.
if performing side effect:
items.stream() .filter(s -> s.contains("b")) .collect(collectors.tolist()); items.foreach(s -> s.setstate("ok"))
Comments
Post a Comment