Java Streams:使用Collectors.toCollection将返回集合修改为自定义类型

问题描述

如何将return集合修改为自定义类型?
我有一个自定义的链表对象,在对它进行某种类型的操作后,我想替换它。

这是我要实现的目标的一个简单示例:

myCustomList = myCustomList.stream()
                           .sorted(Comparator.comparing(user::getId))
                           .collect(Collectors.toCollection(CustomLinkedList::new))

我从这段CustomlinkedList::new代码中得到以下错误。

方法参考中的错误返回类型:无法将CustomLinkedList转换为java.util.Collection

我想我可以将其转换为默认的LinkedList对象,对其进行迭代,然后将节点一个接一个地添加到我的customLinkedList实现中,但这对我来说并不是一个干净的解决方案。

以下是我正在使用的customList的链接:customLinkedList
有办法解决这个问题吗?


更新:

根据Ismail的建议,我设法像这样获得Collector.of的实现:

.collect(Collector.<T,CustomLinkedList<T>>of(
                                     CustomLinkedList::new,CustomLinkedList::add,CustomLinkedList::cloneInto));

但是现在我收到以下错误:

java.lang.ArrayIndexOutOfBoundsException:索引0超出长度0的范围


解决方案:

我完全忘记了我使用的是Spliterators.spliterator,其大小设置为0。将其修复为列表的当前大小可解决此问题。谢谢大家!

解决方法

您可以使用suppliercollect Java流定制Collector.of

myCustomList = myCustomList.stream()
                           .sorted(Comparator.comparing(user::getId))
                           .collect(Collector.of(CustomLinkedList::new,CustomLinkedList::addNewElement,(list1,list2) -> list1.mergeWith(list2)));

Collector.of具有三个参数:

  1. 您要使用的供应商,CustomLinkedList
  2. 如何向供应商添加元素的功能。
  3. 在我的示例中,该函数返回两个合并的不同CustomLinkedList list1list2的结果,当使用并行流处理时,此函数是必需的。

有关示例的更多详细信息,请参见此link

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...