java 8流从类型A的集合创建类型B的集合

标签 java collections java-8 java-stream

这个问题在这里已经有了答案:





Create list of object from another using Java 8 Streams

(4 个回答)


4年前关闭。




我想使用流从类型 B 创建类型 A 的集合。

假设我有两个类

Class Employee{
   String firstName;
   String lastName;
   int age;
   String id;
   String email;
   double salary;
}

Class Person {
  String firstName;
  String lastName;
  String email;
}

要从 Employee 集合创建 Person 集合,我编写了以下代码
public static List<Person> createPersonsFromEmployees(List<Employee> employees) {

        List<Person> persons = new ArrayList<>();

        employees.stream().filter(Object :: nonNull)
                  .forEach(e -> {
                       persons.add(new Person(e.getFirstName(),
                                           e.getLastName(), 
                                           e.getEmail());
                   };)


        return persons;
}

目前,这段代码有效。但我想知道并想知道是否有更好的方法来创建 Person 的集合来自 Employee不使用 forEach .

最佳答案

这是一个更简洁的方法。在流中使用 .forEach() 表明可能有更好的方法来使用 Stream。流旨在具有功能性,并且它们试图远离可变性。

public static List<Person> createPersonsFromEmployees(List<Employee> employees)
    Function<Employee, Person> employeeToPerson = e -> new Person(e.getFirstName, e.getLaseName(), e.getEmail());

    return employees.stream()
                    .filter(Object :: nonNull)
                    .map(employeeToPerson)
                    .collect(Collectors.toList());

}

关于java 8流从类型A的集合创建类型B的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43315161/

相关文章:

java - java中如何测量两次按钮点击之间的时间

java - 我可以使用哪个 Java 集合?

java - 在添加自定义注释和 MethodInterceptor 时,EnhancerByGuice 生成的类导致 Dropwizard 出错

java - Reduce Integer.min 不返回最低元素

java - 什么是 NullPointerException,我该如何解决?

Java - 获取 JSON 对象数组?

java - 通用集合的可能元素类型

java - 如何将已检查的异常从 CompletableFuture 传递到 ControllerAdvice

java - 将 &nbsp 作为字符串处理

dictionary - Groovy:在 map 列表中按键查找/返回 map 的值