Create list of object from another using Java 8 Streams

后端 未结 3 1646
星月不相逢
星月不相逢 2020-11-27 15:36

I\'m trying to understand Java 8 streams. I have two classes:

public class UserMeal {
    protected final LocalDateTime dateTime;

    protected final String         


        
3条回答
  •  一向
    一向 (楼主)
    2020-11-27 16:16

    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 persons = Arrays.asList(
                    new Person("e1", "l1"),
                    new Person("e2", "l1"),
                    new Person("e3", "l2"),
                    new Person("e4", "l2")
            );
    
            List 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
    }
    

提交回复
热议问题