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
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());
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With