Vavr - append 2 Lists of type io.vavr.collection.List into a single List based on the fields

1.1k Views Asked by At

I have the below requirement, I have 2 Lists, one is EmployeeList and DepartmentList now I want to merge/append the 2 lists into another List(finalList) based on the fields in the example below.

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();

Below are the classes: Employee, Department and EmployeeDepartment.

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
}
2

There are 2 best solutions below

0
On

You may iterate on both lists and add the new EmployeeDepartment objects

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

Or using Stream

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

I'm not sure what is the expected output (also EmployeeDepartment has all the fields that Employee has), but if you need to have all the combinations of elements in two lists then crossProduct is what you need:

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());

    }
}

What you get is an iterator with 6 tuples.

If you need to get a Department for every Employee using deptno then it would be much better to convert the second collection to Map<Integer, Department> and use it to map the first collection.