Search code examples
javalistgenericsarraylistconverters

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>


Solution

  • 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.