What I'm looking for is a way to convert a collection of one type to a collection of another type using streams and map WITHOUT having a predefined function/functional interface that converts object A to object B. Java 6 example:
for (ObjectA objA : collectionA) {
ObjectB objB = new ObjectB();
objB.setId(objA.getId());
collectionB.add(objB);
}
I'm looking for something in the lines of:
List<ObjectB> collectionB = collectionA.stream().map(objA -> {
ObjectB objB = new ObjectB();
objB.setId(objA.getId());
return objB;
});
Which of course doesn't work but you get the gist of what I'm trying to do.
After you do the mapping, you have to collect the mapped objects:
List<ObjectB> collectionB = collectionA.stream().map(objA -> {
ObjectB objB = new ObjectB();
objB.setId(objA.getId());
return objB;
}).collect(Collectors.toList());
Your sample code is simply missing the terminal collect
operation, to collect the elements of the Stream<ObjectB>
that was returned from your map
operation into a List<ObjectB>
:
List<ObjectB> collectionB = collectionA.stream().map(objA -> {
ObjectB objB = new ObjectB();
objB.setId(objA.getId());
return objB;
}).collect(Collectors.toList());
If you add to your ObjectB
class a constructor that accepts a parameter of type ObjectA
and sets the ID, you can simplify your code :
i.e. in ObjectB
you add this constructor :
public ObjectB (ObjectA objA)
{
setId(objA.getId());
}
And your code becomes :
List<ObjectB> collectionB = collectionA.stream()
.map(ObjectB::new)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With