如何使用流从列表中的对象数组中获取id?

vkc1a9a2  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(623)

这个问题在这里已经有了答案

基于integerlist[closed](1个答案)过滤对象列表
上个月关门了。
假设我在java中有一个包含id和name的对象列表,我如何只选择id并将其保存到另一个列表中
详细信息[{id:1,name:brown},{id:2,白色},{id:3,name:black}]
我想把所有的身份证都列入新名单。
我试过的是

List<String> ids = details.stream().filter(item -> item.getId()).collect(Collectors.toList());

这会在item.getid()附近引发语法错误

xam8gpfp

xam8gpfp1#

而不是使用 .filter ,您需要使用 .map .
为了使代码更简洁,可以替换 item -> item.getId() 方法参考: Item::getId .
这将是最终结果:

List<String> ids = details.stream()
        .map(Item::getId)
        .collect(Collectors.toList());
wmomyfyw

wmomyfyw2#

样品适合你,

Employee emp1 = new Employee(1,"Ally");
        Employee emp2 = new Employee(2,"Billy");
        ArrayList<Employee> employeeList = new ArrayList<>(Arrays.asList(emp1,emp2));

        List<Integer> collect = employeeList.stream()
                                            .map(Employee::getId)
                                            .collect(Collectors.toList());
        System.out.println("collect = " + collect);

相关问题