简体   繁体   中英

nested arraylist to hashmap in Java8

I have below Objects -

Company.java

private String compName;
private List<Department> departments;

Department.java

private String deptId;
private String deptName;
private List<Employee> employees;

Employee.java

private String empId;
private String legalStatement;

I want to return Map of each employee legal statement -

Map<String, String> legalStatement = new HashMap<>();

For that existing logic is -

for(Department department : departments){
   if(department.getEmployees() != null && 
      department.getEmployees().size() > 0){
      for(Employee employee : department.getEmployees()){
        legalStatement.put(employee.getEmpId(), 
        employee.getLegalStatement());
      } 
   }
}

How I can write same thing in Java 8 Stream API.

You can use stream's filter for if , flatMap for internal employee list and collect to collect as a Map :

Map<String, String> legalStatement = departments.stream()
        .filter(department -> department.getEmployees() != null && !department.getEmployees().isEmpty())
        .flatMap(department -> department.getEmployees().stream())
        .collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));

By using flatMap and ternary operator

Map<String,String> result = departments.stream()
 .flatMap(d->(Objects.nonNull(d.getEmployees()) && !d.getEmployees().isEmpty()) ? d.getEmployees().stream() : Stream.empty())
 .collect(Collectors.toMap(Employee::getEmpId, Employee::getLegalStatement));

As @nullpointer suggestion if there is a chance for duplicate employee id use mergeFunction

public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
                                                Function<? super T,? extends U> valueMapper,
                                                BinaryOperator<U> mergeFunction)

If the mapped keys contains duplicates (according to Object.equals(Object)), the value mapping function is applied to each equal element, and the results are merged using the provided merging function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM