使用具有 java 8 个流的自定义收集器时获取 ClassCastException

Getting a ClassCastException when using a custom Collector with java 8 streams

我有一个自定义 Collector 类型

public class ClusteringCollector extends java.util.stream.Collector<MyModel, Map<String, ClusterModel>, SortedSet<Map.Entry<Integer, ClusterModel>>> {
    @Override
    public Supplier<Map<String, MyOtherModel>> supplier() {
        return HashMap::new;
    }

    @Override
    public BiConsumer<Map<String, ClusterModel>, MyModel> accumulator() {
        return (l, r) -> {
            String mapKey = r.getURI();
            if(l.containsKey(mapKey)) {
                l.get(mapKey).addCluster(r.getCluster());
            } else {
                l.put(mapKey, r.getCluster());
            }
        }
    }

    @Override
    public BinaryOperator<Map<String, ClusterModel>> combiner() {
        return (left, right) -> {
            for(Map.Entry<String, ClusterModel> e : right.entrySet()) {
                e.getValue().setClusterCount(1);
                if(left.containsKey(e.getKey())) {
                    left.get(e.getKey()).merge(e.getValue());
                } else {
                    left.put(e.getKey(), e.getValue());
                }
            }

            return left;
        };
    }

    @Override
    public Function<Map<String, ClusterModel>, SortedSet<Map.Entry<Integer, ClusterModel>>> finisher() {
        return (accumulated) -> {
            SortedSet<Map.Entry<Integer, ClusterModel>> finished = new TreeSet<>((mine, theirs) -> {

               Double t1 = mine.getValue().getClusterCount() * mine.getValue().getClusterWeight();
               Double t2 = theirs.getValue().getClusterCount() * theirs.getValue().getClusterWeight();

               return t2.compareTo(t1);
            });

            Map<Integer, ClusterModel> tempMap = new LinkedHashMap<>();
            for(Map.Entry<String, ClusterModel> e : accumulated.entrySet()) {
                if(tempMap.containsKey(e.getValue().hashCode())) {
                    tempMap.get(e.getValue().hashCode()).merge(e.getValue());
                } else {
                    tempMap.put(e.getValue().hashCode(), e.getValue());
                }
            }

            finished.addAll(tempMap.entrySet());

            return finished;
        };
    }

    @Override
    public Set<Characteristics> characteristics() {
        return EnumSet.of(Characteristics.UNORDERED, Characteristics.IDENTITY_FINISH);
    }
}

我是这样使用收集器的

try (Stream<MyModel> resultStream = generateDataStream()) {
    SortedSet<Map.Entry<Integer, ClusterModel>> clusters = resultStream.collect(new ClusteringCollector()); // This line throws a ClassCastException
}

但问题是,当我尝试 运行 上面的 collect 方法时,我总是收到 ClassCastException。这是堆栈跟踪

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.SortedSet
    com.mycomp.abc.core.services.DefaultClusteringServiceImpl.findClusters(DefaultClusteringServiceImpl.java:78)
    com.mycomp.abc.core.webservices.ClusteringWebService.getClustersFromQuery(ClusteringWebService.java:67)
    com.mycomp.abc.core.webservices.ClusteringWebService$Proxy$_$$_WeldClientProxy.getClustersFromQuery(Unknown Source)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:137)
    org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:296)
    org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:250)
    org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:237)
    org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356)
    org.jboss.resteasy.core.SynchronousDispatcher.invokePropagateNotFound(SynchronousDispatcher.java:217)
    org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:224)
    org.jboss.resteasy.plugins.server.servlet.FilterDispatcher.doFilter(FilterDispatcher.java:62)

谁能告诉我为什么会这样?我没有收到任何编译错误,并且 finisher 正确地将 Map 转换为 SortedSet

发布的代码中有几个错误表明这不是实际代码,但是主要问题是可以识别的。您指定了 IDENTITY_FINISH 特征,尽管您在整理器中进行了复杂的转换。

IDENTITY_FINISH 特征意味着终结器就像 Function.identity(),但在运行时,Stream 实现无法检查通用签名是否与该声明兼容。当它使用此特性决定跳过整理器时,它只会 return 容器对象,在您的情况下是 HashMap,当然不能分配给 SortedSet .

说到底,还是这个错误的好结果。更糟糕的是,如果容器和结果类型兼容并且跳过一个非平凡的终结者一开始没有被注意到。所以在指定 IDENTITY_FINISH 特征时要小心。

请注意,当您不实现 Collector,而是通过将函数传递给 Collector.of(…) 来构造一个时,您永远不需要指定该特征,因为它将根据是否您是否指定了修整函数。对于没有finisher的重载方法,泛型签名甚至会保证容器类型匹配结果类型。