Paul
Paul

Reputation: 259

Java Convert List<TypeA> to List<TypeB>

For example

class TypeA {
    private String a;
    private String b;
    private String c;
}

class TypeB {
    private String a;
}

Now I have a list of TypeA, and I only need the information a from TypeA. What's the most efficient way to convert List<TypeA> to List<TypeB>

Upvotes: 1

Views: 1421

Answers (3)

M. Justin
M. Justin

Reputation: 21114

The Stream.map method is well suited for this type of data transformation.

List<TypeB> bList = aList.stream().map(typeA -> new TypeB(typeA.a)).toList();

Upvotes: 0

Nikolas
Nikolas

Reputation: 44398

Efficient in what way? In terms of maintainability and clarity, I vote for object mapping libraries such as ModelMapper or MapStruct that are based on both the reflection and annotations. In case of MapStruct, you can define a mapping for the objects TypeA and TypeB and use the relevant method within the same mapping interface.

@Mapper
public interface TypeA Mapper {

    @Mapping(target="a")
    TypeB typeAToTypeB(TypeA typeA) 

    List<TypeB> listOfTypeAToListOfTypeB(List<TypeA> list);
}

You can always use just a simple iteration using or a simple for-loop:

List<TypeB> listOfTypeB = listOfTypeA.stream()
    .map(typeA -> new TypeB(typeA.getA())
    .collect(Collectors.toList());

Upvotes: 2

Andreas
Andreas

Reputation: 159086

Answer depends on what you mean by "efficient".

// Option 1
List<TypeB> bList = new ArrayList<>();
for (TypeA a : aList) {
    bList = new TypeB(s.getA());
}

// Option 2
List<TypeB> bList = aList.stream()
        .map(TypeA::getA)
        .map(TypeB::new)
        .collect(Collectors.toList());

// Option 3
List<TypeB> bList = aList.stream().map(a -> new TypeB(s.getA())).collect(toList());

The first performs best. That is one type of efficiency.

The second and third are single statements. That is another type of efficiency.

Upvotes: 2

Related Questions