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
Personobjects, representing individuals in our application. - Next, we invoke
stream()on thepersonslist to obtain a stream of elements. we then use themapmethod to transform eachPersonobject into anEmployeeobject, using a lambda expression to create a newEmployeeinstance with the relevant properties. - Next, we use the
collect(Collectors.toList())method to gather the transformedEmployeeobjects into a new list and finally, we print the details of eachEmployeeto 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.
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
personListthat holds instances of thePersonclass. ThreePersonobjects are instantiated with their names along with their respective ages, and they are added to thepersonList. - Next, a new
employeeListis created to hold instances of theEmployeeclass. TheforEachmethod is used to iterate over eachPersonobject in thepersonList. - For each
Person, a correspondingEmployeeobject is created using theEmployeeconstructor. The employee’snameandageare taken from thePersonobject, and a random employee ID is generated using thegenerateEmployeeIdmethod. - The newly created
Employeeobjects are then added to theemployeeList. Finally, theemployeeListis iterated usingforEachmethod, and for eachEmployeeobject, 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
Listnamedpersonsis created, containing instances of thePersonclass. EachPersonobject is instantiated with anameand anage. persons.stream()method converts the list ofPersonobjects into a stream..map(Person::getName)applies themapmethod to transform eachPersonobject into its corresponding name. The method referencePerson::getNameis used to extract the name from eachPersonobject..collect(Collectors.toList())collects the stream elements into a new list ofStringobjects.
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.
You can download the full source code of this example here: Generate a List of Objects from a Different Type Using Java


