我有 2 個(gè)員工名單。第一個(gè)列表包含姓名和員工 ID,第二個(gè)列表包含員工 ID 和手機(jī)號(hào)碼。員工 ID 是主鍵。要求是使用流式傳輸方式獲取包含 id、姓名和手機(jī)號(hào)碼的列表。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貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以使用第一個(gè)列表創(chuàng)建
empId
到它們的映射。name
Map<Integer, String> empIdToName = employeeNameList.stream() .collect(Collectors.toMap(Employee::getId, Employee::getName, (a, b) -> a));
使用這樣的映射進(jìn)一步創(chuàng)建對象,同時(shí)迭代第二個(gè)映射并查找該映射,例如:
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());
添加回答
舉報(bào)
0/150
提交
取消