假设有一个名为 'Person' 的类,包含属性 'id' 和 'name',现在有一个 List 集合,需要获取其 'id' 集合,可以使用 lambda 表达式实现:

List<Person> personList = new ArrayList<>();
// 假设已经将数据添加进 personList 集合中
List<Integer> idList = personList.stream().map(Person::getId).collect(Collectors.toList());

其中,map(Person::getId) 表示将每个 'Person' 对象映射为其对应的 'id' 值,最后使用 collect(Collectors.toList()) 将所有 'id' 值收集为一个 List 对象。

Java Lambda 表达式获取 List 集合中所有 ID 的方法

原文地址: https://www.cveoy.top/t/topic/lVgn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录