使用两个列表在流中进行流传输

我有 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));

    }

}


慕斯709654
浏览 85回答 1
1回答

天涯尽头无女友

您可以使用第一个列表创建empId到它们的映射。nameMap<Integer,&nbsp;String>&nbsp;empIdToName&nbsp;=&nbsp;employeeNameList.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toMap(Employee::getId,&nbsp;Employee::getName,&nbsp;(a,&nbsp;b)&nbsp;->&nbsp;a));使用这样的映射进一步创建对象,同时迭代第二个映射并查找该映射,例如:List<Employee>&nbsp;employees&nbsp;=&nbsp;employeeMobileList.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.filter(item&nbsp;->&nbsp;empIdToName.containsKey(item.getId())) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(i&nbsp;->&nbsp;new&nbsp;Employee(i.getId(),&nbsp;empIdToName.get(i.getId()),&nbsp;i.getMobileNo())) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java