我有 2 个员工名单。第一个列表包含姓名和员工 ID,第二个列表包含员工 ID 和手机号码。员工 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)); }}
1 回答
天涯尽头无女友
TA贡献1831条经验 获得超9个赞
您可以使用第一个列表创建
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());
添加回答
举报
0/150
提交
取消