How to Convert a List of Objects to Another List of Objects Using Java Streams?

Java streams have become a powerful tool for manipulating collections of data. They allow for concise and expressive code, making it easier to perform complex operations on collections. One common scenario is converting a list of objects into another list of objects, applying transformations or filters along the way. In this blog post, we will explore how to accomplish this task using Java streams.

Define the Source and Target Objects:

To begin, let’s assume we have a source list of objects, and we want to convert it into a target list of objects. Make sure you have appropriate classes for both the source and target objects. For the sake of this example, let’s consider a simple scenario where we have a list of “Person” objects and want to convert them into a list of “PersonDTO” objects.

class Person {
    private String name;
    private int age;

    // constructors, getters, and setters
}

class PersonDTO {
    private String fullName;
    private int age;

    // constructors, getters, and setters
}

Step 2: Use Java Streams to Convert the List To convert the list of objects, we’ll leverage the power of Java streams. Streams provide a functional and declarative approach to perform operations on collections. Here’s how we can use streams to transform our list of “Person” objects to a list of “PersonDTO” objects.

List<Person> persons = // Your source list of Person objects

List<PersonDTO> personDTOs = persons.stream()
    .map(person -> {
        PersonDTO personDTO = new PersonDTO();
        personDTO.setFullName(person.getName());
        personDTO.setAge(person.getAge());
        return personDTO;
    })
    .collect(Collectors.toList());

Let’s break down the above code snippet:

  • We start by calling the stream() method on the source list of objects (persons in this case). This converts the list into a stream of elements.
  • The map() method is then used to transform each element of the stream. Here, we create a new PersonDTO object, set its properties based on the corresponding properties of the source Person object, and return the new PersonDTO object.
  • Finally, we call the collect() method to accumulate the transformed elements into a new list using the Collectors.toList() collector.

Step 3: Handle Potential Exceptions In real-world scenarios, the conversion process may involve some operations that can throw exceptions. To handle such cases gracefully, consider adding exception handling within the map() operation. For example:

List<PersonDTO> personDTOs = persons.stream()
    .map(person -> {
        try {
            PersonDTO personDTO = new PersonDTO();
            personDTO.setFullName(person.getName());
            personDTO.setAge(person.getAge());
            return personDTO;
        } catch (Exception e) {
            // Handle the exception or log an error message
            return null; // or return a default value
        }
    })
    .filter(Objects::nonNull) // Filter out any null elements
    .collect(Collectors.toList());

In the code snippet above, we catch any exceptions that may occur during the mapping process. If an exception is caught, you can handle it appropriately, such as logging an error message or returning a default value. Additionally, we filter out any null elements using the filter() method before collecting the results.

In this blog post, we explored how to convert a list of objects to another list of objects using Java streams. We saw how streams provide a concise and expressive way to perform transformations on collections, using the map() method in combination with lambda expressions. Additionally, we discussed the importance of handling exceptions during the conversion process to ensure robustness in real-world scenarios. By leveraging the power of Java streams, you can write cleaner and more efficient code when working with collections of objects in your Java applications.