首页 > 解决方案 > 为什么 Collectors.partitioningBy 返回 Object 而不是 Map

问题描述

我创建了一组基于 Employee 类的不同属性的谓词,并使用默认方法和/或 Predicate 将它们组合成一个谓词,并在 Collectors.partitioningBy 方法中使用这个组合谓词。

虽然代码在 Eclipse 上编译和执行良好,但构建我的项目却给了我错误:

不兼容的类型:java.lang.Object 无法转换为 java.util.Map<java.lang.Boolean,java.util.List<com.MyProj.Employee>>

Predicate<Employee> addressSectionNull = emp-> emp== null || emp.getAddress() == null;
Predicate<Employee> isBlankLane = emp -> StringUtils.isBlank(emp.getAddress().getLane());
Predicate<Employee> notValidCity = emp -> "NA".equalsIgnoreCase(emp.getAddress().getCity());


Predicate notEligible =
    addressSectionNull.or(isBlankLane).or(notValidCity);
Map<Boolean, List<Employee>> empValidityMap =
    employees.parallelStream().collect(Collectors.partitioningBy(notEligible));

标签: javajava-8java-streamcollectors

解决方案


改变

Predicate notEligible = ...

Predicate<Employee> notEligible = ...

原因:Collectors.partitioningBy(T predicate)将返回一个Collector<T, ?, Map<Boolean, List<T>>>. 当您的 Predicate 没有泛型类型时, T 将是Object.


推荐阅读