Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a collection to another collection type without predefined method in Java 8

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.

like image 621
PentaKon Avatar asked Jul 22 '15 10:07

PentaKon


2 Answers

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());
like image 200
Konstantin Yovkov Avatar answered Oct 11 '22 10:10

Konstantin Yovkov


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());
like image 24
Eran Avatar answered Oct 11 '22 10:10

Eran