如何解决Java Streams:使用Collectors.toCollection将返回集合修改为自定义类型
如何将return集合修改为自定义类型?
我有一个自定义的链表对象,在对它进行某种类型的操作后,我想替换它。
这是我要实现的目标的一个简单示例:
myCustomList = myCustomList.stream()
.sorted(Comparator.comparing(user::getId))
.collect(Collectors.toCollection(CustomLinkedList::new))
我从这段CustomlinkedList::new
代码中得到以下错误。
我想我可以将其转换为默认的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。将其修复为列表的当前大小可解决此问题。谢谢大家!
解决方法
您可以使用supplier
为collect
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
具有三个参数:
- 您要使用的供应商,
CustomLinkedList
。 - 如何向供应商添加元素的功能。
- 在我的示例中,该函数返回两个合并的不同
CustomLinkedList
list1
和list2
的结果,当使用并行流处理时,此函数是必需的。
有关示例的更多详细信息,请参见此link。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。