Vavr - 根据字段将 io.vavr.collection.List 类型的 2 个列表附加到单个列表中

问题描述

我有以下要求,我有 2 个列表,一个是 EmployeeList 和 DepartmentList 现在我想根据下面示例中的字段将这 2 个列表合并/附加到另一个 List(finalList) 中。

List<Employee> list = List.of( new Employee(1,"aba",101),new Employee(2,"cdc",102),new Employee(3,"ded",102));
List<Department> list1 = List.of( new Department(101,"Dep1"),new Department(102,"Dep2"));
List <EmployeeDepartment> finalList = List.empty();

以下是类:EmployeeDepartmentEmployeeDepartment

public class EmployeeDepartment {

    Integer deptno;
    Integer empid;
    String empname;
---setters and Getters
}
public class Department {
    Integer deptno;
    String depname;
---setters and Getters
}
public class Employee {

    Integer empid;
    String empname;
    Integer deptno;
---setters and Getters
}

解决方法

您可以对两个列表进行迭代并添加新的 EmployeeDepartment 对象

List<EmployeeDepartment> finalList = new ArrayList<>();
for (Employee e : list) {
    for (Department d : list1) {
        finalList.add(new EmployeeDepartment(e.getEmpid(),e.getEmpname(),d.getDeptno()));
    }
}

或者使用 Stream

List<EmployeeDepartment> finalList = list.stream()
        .flatMap(e -> list1.stream().map(d -> new EmployeeDepartment(e.getEmpid(),d.getDeptno())))
        .collect(Collectors.toList());
,

我不确定预期的输出是什么(还有 EmployeeDepartment 具有 Employee 具有的所有字段),但是如果您需要在两个列表中包含元素的所有组合,那么 {{ 1}} 正是您所需要的:

crossProduct

你得到的是一个带有 6 个元组的迭代器。

如果您需要使用 class Lol { public static void main(String[] args) { List<Employee> list = List.of( new Employee(1,"aba",101),new Employee(2,"cdc",102),new Employee(3,"ded",102) ); List<Department> list1 = List.of( new Department(101,"Dep1"),new Department(102,"Dep2") ); final Iterator<Tuple2<Employee,Department>> tuple2s = list.crossProduct(list1); System.out.println(tuple2s.size()); } } 为每个 Department 获取 Employee,那么最好将第二个集合转换为 deptno 并使用它来映射第一个合集。