Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copying each field of an object of Class A to each field of an object of classB in list

I have a list of Objects of ClassA(fields for example: id,name,phone)and need to set each of those fields in to another list of Objects of ClassB (fields: studentId,studentName and studentPhone). is there a simple way in Java 8? Basically, ClassA is my DTO and ClassB is DAO object. For example:

List<ClassA> list1 = new ArrayList<>();
list1.add(new ClassA(12,"John","1111111111"))
List<ClassB> list2 = new ArrayList<>();

here, I want to set each element of ClassA to ClassB object and add into list2

like image 284
Jacob Avatar asked Feb 04 '19 16:02

Jacob


2 Answers

This is pretty standard. You could use Stream and map method to modify an instance of ClassA.

Assume that:

public class ClassA {
    private final int id;
    private final String name;
    private final String phone;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getPhone() {
        return phone;
    }
}

public class ClassB {
    private int studentId;
    private String studentName;
    private String studentPhone;

    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public void setStudentPhone(String studentPhone) {
        this.studentPhone = studentPhone;
    }
}

Then your code could look like this:

List<ClassA> list1 = Collections.emptyList();
List<ClassB> list2 = list1.stream()
                          .map(a -> {
                              ClassB b = new ClassB();
                              b.setStudentId(a.getId());
                              b.setStudentName(a.getName());
                              b.setStudentPhone(a.getPhone());
                              return b;
                          })
                          .collect(Collectors.toList());
like image 158
oleg.cherednik Avatar answered Sep 23 '22 01:09

oleg.cherednik


If ClassB had a similar constructor as that of ClassA, then all you needed to do would be:

List<ClassB> classBList = classAList.stream()
        .map(a -> new ClassB(a.getId(), a.getName(), a.getPhone()))
        .collect(Collectors.toList());
like image 20
Naman Avatar answered Sep 25 '22 01:09

Naman