How to convert a list with properties to a another list the java 8 way?

Ivan :

There is a List A with property Developer. Developer schema likes that:

@Getter
@Setter
public class Developer {
    private String name;
    private int age;

    public Developer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Developer name(String name) {
        this.name = name;
        return this;
    }

    public Developer name(int age) {
        this.age = age;
        return this;
    }
}

List A with properties:

List<Developer> A = ImmutableList.of(new Developer("Ivan", 25), new Developer("Curry", 28));

It is demanded to convert List A to List B which with property ProductManager and the properties is same as the ones of List A.

@Getter
@Setter
public class ProductManager {
    private String name;
    private int age;

    public ProductManager(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public ProductManager name(String name) {
        this.name = name;
        return this;
    }

    public ProductManager name(int age) {
        this.age = age;
        return this;
    }
}

In the old days, we would write codes like:

public List<ProductManager> convert() {
    List<ProductManager> pros = new ArrayList<>();
    for (Developer dev: A) {
        ProductManager manager = new ProductManager();
        manager.setName(dev.getName());
        manager.setAge(dev.getAge());
        pros.add(manager);
    }
    return pros;
}

How could we write the above in a more elegant and brief manner with Java 8?

Ramachandran.A.G :

you will have to use something like below :

List<ProductManager> B = A.stream()
        .map(developer -> new ProductManager(developer.getName(), developer.getAge()))
        .collect(Collectors.toList());

// for large # of properties assuming the attributes have similar names //other wise with different names refer this

List<ProductManager> B = A.stream().map(developer -> {
            ProductManager productManager = new ProductManager();
            try {
                PropertyUtils.copyProperties(productManager, developer);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return productManager;
        }).collect(Collectors.toList());

        B.forEach(System.out::println);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=450250&siteId=1