java - 从嵌套集合结构中获取平面格式的所有元素
问题描述
我需要以类似于 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。
问候
解决方案
使用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());
推荐阅读
- python-3.x - 从网站中的不同链接获取律师详细信息
- javascript - 如何在 SparkAR 中为对象添加旋转?
- php - 单引号内的单引号删除正斜杠
- json - 我可以使用 if/then 来强制执行与先前给出的相矛盾的属性约束吗?
- python - 使用正则表达式从 Python 中的 SQL 查询中删除别名?
- java - 想使用泛型类型
- vue.js - 如何将xml模板放入vue组件属性中
- firebase - 如果“SignInWithFacebook”不再可用,我该如何创建一个带有firebase的facebook登录页面?
- python - 如何按时间戳(降序)从 mongoengine 中的查询集上的 objectId 排序?
- swift - 光不随相机移动 - SceneKit