Java lambda expression - display and then change list?

Using the Java 8 lambda expression, I am trying to do something like this.

List<NewObject> objs = ...; for (OldObject oldObj : oldObjects) { NewObject obj = oldObj.toNewObject(); obj.setOrange(true); objs.add(obj); } 

I wrote this code.

 oldObjects.stream() .map(old -> old.toNewObject()) .forEach({new.setOrange("true")}) .collect(Collectors.toList()); 

This code is incorrect because I am trying to do .collect() to return .forEach() , but forEach invalid and does not return a list.

How should this be structured?

+2
java lambda java-8 java-stream
Nov 06 '15 at
source share
2 answers

You can use the Stream peek method , which returns a Stream , because it is an intermediate operation. Usually it should not have a side effect (it should be "non-interfering"), but in this case I think that the side effect ( setOrange(true) ) is designed and in order.

 List<NewObject> newObjects = oldObjects.stream() .map(OldObject::toNewObject) .peek( n -> n.setOrange(true)) .collect(Collectors.toList()); 

This is about as verbose as your code without threads, so you can choose which method to use.

+5
Nov 06 '15 at 0:22
source share

You can use peek .

 List<NewObject> list = oldObjects.stream() .map(OldObject::toNewObject) .peek(o -> o.setOrange(true)) .collect(Collectors.toList()); 

Alternatively, you can mutate the elements after forming the list.

 List<NewObject> list = oldObjects.stream() .map(OldObject::toNewObject) .collect(Collectors.toList()); list.forEach(o -> o.setOrange(true)); 
+5
Nov 06 '15 at 0:22
source share



All Articles