首页 > 解决方案 > 如何从 Java Spring Boot 中的列表对象中获取数组列表?

问题描述

public class EmployeeDetails {  
// this itself is an Array List defined in other model as List<EmployeeDetails> employeeDetails
    String name;
    String age;
    List<EmployeeDetails> employee    // How to get this ?
}

我在下面尝试过,但无法访问该数组列表中的所有值..

public List<EmployeeDetails> printEmployeeDetails(List<EmployeeDetails> data) {
  return data.getEmployeeDetails().stream().findFirst().get().getEmployee()
  // this is only giving me first list. How can i access all values present in this Array List ?
}

标签: javaspringspring-boot

解决方案


为了从另一个流中获取列表的流,您可以使用 flatMap 运算符。

return data.getEmployeeDetails()
  .stream()
  .flatMap(employee -> employee.getEmployee().stream())
  .collect(Collectors.toList());

我不确定这个答案是否足够,您没有指定它是否应该递归地获取所有员工以及重复项会发生什么。


推荐阅读