简体   繁体   English

在Java8中将arraylist嵌套到hashmap

[英]nested arraylist to hashmap in Java8

I have below Objects - 我有以下对象-

Company.java 公司.java

private String compName;
private List<Department> departments;

Department.java 部门.java

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

Employee.java 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. 如何在Java 8 Stream API中编写相同的内容。

You can use stream's filter for if , flatMap for internal employee list and collect to collect as a Map : 您可以将流的filter用于ifflatMap用于内部employee列表,并collectMap收集:

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 通过使用flatMapternary运算符

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 作为@nullpointer建议,如果有可能出现重复的员工ID,请使用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. 如果映射的键包含重复项(根据Object.equals(Object)),则将值映射函数应用于每个equal元素,然后使用提供的合并函数合并结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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