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 type void.

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

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -