我有2个员工列表。一个列表包含姓名和employeeId,第二个列表包含employeeId和手机号码。员工ID是主键。 要求是使用流媒体获取包含ID,名称和移动电话号码的列表。
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Employee emp1 = new Employee(101, "Shiv1");
Employee emp2 = new Employee(102, "Shiv2");
Employee emp3 = new Employee(103, "Shiv3");
Employee emp4 = new Employee(104, "Shiv4");
Employee emp5 = new Employee(101, 00001);
Employee emp6 = new Employee(101, 00002);
Employee emp7 = new Employee(101, 00003);
Employee emp8 = new Employee(101, 00004);
List<Employee> employeeNameList = new ArrayList<Employee>();
employeeNameList.add(emp1);
employeeNameList.add(emp2);
employeeNameList.add(emp3);
employeeNameList.add(emp4);
List<Employee> employeeMobileList = new ArrayList<Employee>();
employeeMobileList.add(emp5);
employeeMobileList.add(emp6);
employeeMobileList.add(emp7);
employeeMobileList.add(emp8);
employeeNameList.stream()
.filter(item -> item.getId() == 3)
.map(i -> i.setMobileNo(9089));
}
}
答案 0 :(得分:1)
您可以使用第一个列表创建empId
到其name
的映射。
Map<Integer, String> empIdToName = employeeNameList.stream()
.collect(Collectors.toMap(Employee::getId, Employee::getName, (a, b) -> a));
使用这种映射来进一步创建对象,同时遍历第二个并查找该映射,例如:
List<Employee> employees = employeeMobileList.stream()
.filter(item -> empIdToName.containsKey(item.getId()))
.map(i -> new Employee(i.getId(), empIdToName.get(i.getId()), i.getMobileNo()))
.collect(Collectors.toList());