I\'m trying to understand Java 8 streams. I have two classes:
public class UserMeal {
protected final LocalDateTime dateTime;
protected final String
If you want to iterate over a list and create a new list with "transformed" objects, you should use the map()
function of stream + collect()
. In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.
public class Test {
public static void main(String[] args) {
List<Person> persons = Arrays.asList(
new Person("e1", "l1"),
new Person("e2", "l1"),
new Person("e3", "l2"),
new Person("e4", "l2")
);
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.map(p -> new Employee(p.getName(), p.getLastName(), 1000))
.collect(Collectors.toList());
System.out.println(employees);
}
}
class Person {
private String name;
private String lastName;
public Person(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
// Getter & Setter
}
class Employee extends Person {
private double salary;
public Employee(String name, String lastName, double salary) {
super(name, lastName);
this.salary = salary;
}
// Getter & Setter
}
What you are possibly looking for is map()
. You can "convert" the objects in a stream to another by mapping this way:
...
.map(userMeal -> new UserMealExceed(...))
...
An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping
does the same in one step:
//...
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.collect(
Collectors.mapping(
p -> new Employee(p.getName(), p.getLastName(), 1000),
Collectors.toList()));
Detailed example can be found here