Create list of object from another using Java 8 Streams

后端 未结 3 1632
星月不相逢
星月不相逢 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<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
    }
    
    0 讨论(0)
  • 2020-11-27 16:17

    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(...))
    ...
    
    0 讨论(0)
  • 2020-11-27 16:25

    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

    0 讨论(0)
提交回复
热议问题