首页 > 解决方案 > 从嵌套集合结构中获取平面格式的所有元素

问题描述

我需要以类似于 flatMap 的方式取回数据,但在某些情况下它不起作用。以下是详细信息。下面是伪代码

class Employee {
 String name;
 int age;
}

Employee emp1 = new Employee("Peter",30);
Employee emp2 = new Employee("Bob",25);

Set<Employee> empSet1 = new HashSet();
empSet1.add(emp1);
empSet1.add(emp2);

Employee emp3 = new Employee("Jack",31);
Employee emp4 = new Employee("Laura",27);

Set<Employee> empSet2 = new HashSet();
empSet2.add(emp3);
empSet2.add(emp4);


Map<String,Set<Employee>> empLocationMap = new HashMap();

empLocationMap.put("location1",empSet1);
empLocationMap.put("location2",empSet2);


Set<Employee> empSet = getEmployeeSetForLocation("location1",empLocationMap);


private static Set getEmployeeSetForLocation(String location,Map<String,Set<Employee>> locationEmpMap) {
    Object filteredObject = locationMap.entrySet().stream().filter(element-> element.getKey().equals(location)).flatMap(element-> Stream.of(element)).collect(Collectors.toSet());
    
return new HashSet(filteredObject );
}

检查时方法 getEmployeeSetForLocation 中的过滤对象显示包含 1 个元素,并且该元素是包含 2 个元素的 Set 类型。我想知道,我可以在上述逻辑中进行哪些修改以进一步展平结构,以便过滤对象显示一个包含 2 个元素的集合。任何指针都会有所帮助。我正在使用 Java 8。

问候

标签: java

解决方案


使用flatMap,将stream of映射MapEntry到stream ofEmployee

 Set<Employee> filteredObject = locationMap.entrySet().stream()
      -- Here you have stream of Map.Entry, where value is employee
      .filter(element -> element.getKey().equals(location)) 
      -- And here is how to convert this stream to Stream<Employee>
      .flatMap(s -> s.getValue().stream())
      .collect(Collectors.toSet());

推荐阅读