Core Java

Generate a List of Objects from a Different Type Using Java 8

In Java programming, how to generate a list of objects from a different type has become much simpler thanks to the introduction of Java 8 and its powerful Stream API. Consider a scenario where we have a list of Person objects, and we need to convert them into a list of Employee objects. This article explores how to achieve this conversion efficiently using Java 8 Streams and the List.forEach() method in Java.

1. Understanding the Scenario

Let’s imagine a scenario where we have a list of Person objects, each with attributes like name and age. Now, we realize the need to introduce a differentiation between ordinary individuals and employees. To accomplish this, we decided to create a new class, Employee, extending the Person class, with an additional property, employeeId.

1.1 Classes: Person and Employee

Firstly, let’s define the classes Person and Employee. These classes represent individuals with some attributes:

public class Person {

    private String name;
    private int age;

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

    // getters and setters
}

public class Employee extends Person{
    
    private int employeeId;

    public Employee(String name, int age, int employeeId) {
        super(name, age);
        this.employeeId = employeeId;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    
}

Both classes have a name and age attribute, and Employee has an additional employeeId attribute.

2. The Java Streams Approach

Here’s an example of how we can convert a List<Person> to a List<Employee> using Java streams.

public class PersonToEmployeeConverter {

    public static void main(String[] args) {
        
        // Sample list of Person objects
        List<Person> persons = List.of(
                new Person("Thomas", 30),
                new Person("Sarah", 25),
                new Person("Bill", 35)
        );

        // Convert List<Person> to List<Employee> using Java streams
        List<Employee> employees = persons.stream()
                .map(person -> new Employee(person.getName(), person.getAge(), generateEmployeeId()))
                .collect(Collectors.toList());

        // Print the result
        employees.forEach(employee -> System.out.println("Employee: " + employee.getName() +
                ", Age: " + employee.getAge() +
                ", Employee ID: " + employee.getEmployeeId()));
    }

    // A simple method to generate unique employee IDs
    private static int generateEmployeeId() {
        
        // return a random number for demonstration purposes
        return (int) (Math.random() * 1000);
    }
}

Let’s break down the code to see how it works:

  • We start with a sample list of Person objects, representing individuals in our application.
  • Next, we invoke stream() on the persons list to obtain a stream of elements. we then use the map method to transform each Person object into an Employee object, using a lambda expression to create a new Employee instance with the relevant properties.
  • Next, we use the collect(Collectors.toList()) method to gather the transformed Employee objects into a new list and finally, we print the details of each Employee to the console.

Note: In the above class, we have used the generateEmployeeId() method to generate unique employee IDs. In a real-world scenario, we might use a database sequence, UUIDs, or any other way to make sure each employee ID is different.

Executing the program will result in the displayed output, showcasing a list of newly created employees as depicted in Fig 1.

Fig 1: Output - Generate a List of Objects from a Different Type Using Java Streams
Fig 1: Output – Generate a List of Objects from a Different Type Using Java Streams

3. Using List.forEach() Method

To convert a List of Person objects to a List of Employee objects, we can utilize the List.forEach() method and lambda expressions like this:

public class PersonToEmployee {

    public static void main(String[] args) {
        
        // Create a list of Person objects
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("John", 25));
        personList.add(new Person("Michelle", 30));
        personList.add(new Person("James", 28));

        // Convert the list of Person objects to a list of Employee objects using List.forEach()
        List<Employee> employeeList = new ArrayList<>();
        personList.forEach(person -> {
            Employee employee = new Employee(person.getName(), person.getAge(), generateEmployeeId());
            employeeList.add(employee);
        });

        // Print the converted list of Employee objects
        employeeList.forEach(employee -> System.out.println("Employee: " + employee.getName() + ", Employee ID: " + employee.getEmployeeId()));
    }
    
        // A simple method to generate unique employee IDs
    private static int generateEmployeeId() {      
        // return a random number for demonstration purposes
        return (int) (Math.random() * 100);
    }
}

In the above code:

  • We begin by creating a personList that holds instances of the Person class. Three Person objects are instantiated with their names along with their respective ages, and they are added to the personList.
  • Next, a new employeeList is created to hold instances of the Employee class. The forEach method is used to iterate over each Person object in the personList.
  • For each Person, a corresponding Employee object is created using the Employee constructor. The employee’s name and age are taken from the Person object, and a random employee ID is generated using the generateEmployeeId method.
  • The newly created Employee objects are then added to the employeeList. Finally, the employeeList is iterated using forEach method, and for each Employee object, the employee’s name and ID are printed to the console.

4. Convert List of Persons to List of String

Imagine we have a list of objects of type Person, and we want to create a new list containing only their names, which are of type String. We can accomplish this in Java by using the following code snippet.

public class ObjectTransformationExample {

    public static void main(String[] args) {
        // Create a list of Person objects
        List<Person> persons = Arrays.asList(
                new Person("John", 40),
                new Person("Shedrach", 50),
                new Person("Fred", 60)
        );

        // Convert the list of Person objects to a list of String objects (names)
        List<String> names = persons.stream()
                .map(Person::getName)
                .collect(Collectors.toList());
        
        // Convert the list of Person objects to a list of Integer objects (age)
        List<Integer> age = persons.stream()
                .map(Person::getAge)
                .collect(Collectors.toList());

        // Print the result
        System.out.println(names);
        System.out.println(age);
    }
}

Here is a breakdown of the provided code snippet:

  • Firstly, a List named persons is created, containing instances of the Person class. Each Person object is instantiated with a name and an age.
  • persons.stream() method converts the list of Person objects into a stream.
  • .map(Person::getName) applies the map method to transform each Person object into its corresponding name. The method reference Person::getName is used to extract the name from each Person object.
  • .collect(Collectors.toList()) collects the stream elements into a new list of String objects.

5. Conclusion

In this article, we’ve explored the process of how to generate a list of objects from a different type using Java 8 streams and the List.forEach() method. In conclusion, converting List of objects from one type to another is a common operation in Java programming, and leveraging Java 8 streams and the List.forEach() method along with lambda expressions provides a neat and straightforward solution to accomplish this.

6. Download the Source Code

This was an example of how to generate a List of objects from a different type using Java 8.

Download
You can download the full source code of this example here: Generate a List of Objects from a Different Type Using Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button