public class FetchVarableList {
public static void main(String[] args) {
List<List<Employee>> empsList = new ArrayList<>();
Employee e1 = new Employee(1, "Abi", "Fin", 2000);
Employee e2 = new Employee(2, "Chandu", "OPs", 5000);
Employee e3 = new Employee(3, "mahesh", "HR", 8000);
Employee e4 = new Employee(4, "Suresh", "Main", 1000);
List<Employee> empList = new ArrayList<>();
empList.add(e1); empList.add(e2);
List<Employee> empList2 = new ArrayList<>();
empList2.add(e3); empList2.add(e4);
empsList.add(empList);
empsList.add(empList2);
}
}
在此代码上方是empList2中的empList,e3,e4中的雇员e1,e2的列表 这两个雇员名单都添加到empslist,我想在单个整数列表中获取所有员工编号
如何从java8中的一个列表中获取所有员工编号列表
答案 0 :(得分:7)
List<Integer> numbers = empsList.stream()
.flatMap(List::stream)
.map(Employee::getNumber)
.collect(Collectors.toList());
答案 1 :(得分:0)
List<Integer> numbers = Stream.concat(empList.stream(), empList2.stream())
.map(Employee::getNumber)
.collect(Collectors.toList());
答案 2 :(得分:0)
结合 JB Nizet 和 ahmet kamaran 的答案,您可以避免创建列表列表(empsList
)通过连接2个列表:
List<Integer> numbers = Stream.concat(empList.stream(), empList2.stream())
.map(Employee::getNumber)
.collect(Collectors.toList());