Search code examples
javadto

Java Converting Classes


I have a class like:

Student
-name
-surname
-address
-number

and I have a DTO for it like:

StudentDTO
-name
-surname
-number

I will send my student class to another class just with name, surname and number fields(I mean not with all fields) and I decided to name it as DTO (I am not using serializing or etc. just I send this class's object as parameter to any other class's methods).

However lets assume that I have a line of code like that:

getAllStudents();

and it returns:

List<Student>

but I want to assign it to a variable that:

List<StudentDTO>

How can I convert them easily?

PS: I can't change my getAllStudents(); method's inside. I have list of students and want a fast and well-designed way to convert a list of objects into another list of objects.


Solution

  • public StudentDTO convert() {
        StudentDTO newDTO = new StudentDTO(name, surname, number);
        return newDTO;
    }
    

    And you can implement this as a public method.

    This, obviously, would be abstracted out into a larger convert method that could do batch processing. Another alternative would be to implement Cloneable and create a specific implementation just for Student -> StudentDTO.

    Iterative example:

    List<StudentDTO> myList = new ArrayList<>();
        for (Student s : collection) {
            myList.add(s.convert());
        }
        return myList;