I have the following Java6 and Java8 code:
List<ObjectType1> lst1 = // a list of ObjectType1 objects
List<ObjectType2> lst2 = // a list of ObjectType1 objects, same size of lst1
List<ObjectType3> lst3 = new ArrayLis<ObjectType3>(lst1.size());
for(int i=0; i < lst1.size(); i++){
lst3.add(new ObjectType3(lst1.get(i).getAVal(), lst2.get(i).getAnotherVal()));
}
Is there any way in Java8 to handle the previous for in a more concise way using Lambda?
You could create a method that transforms two collections into a new collection, like this:
The important part here is that it will map the obtained
iteratorA.next()
anditeratorB.next()
into a new object.It is called like this:
In your example it would be:
Where for example
Pair::new
is a shorthand for the lamdda(t, u) -> new Pair(t, u)
.I haven't found a way to update 1 stream to another, however, I accomplished a similar feat using a Map. :)
A Stream is tied to a given iterable/Collection so you can't really "iterate" two collections in parallel.
One workaround would be to create a stream of indexes but then it does not necessarily improve over the for loop. The stream version could look like: