[英]Confusion over the syntax: Set<String> set = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new))
[英]Java Streams: modifying return collection to a custom type with Collectors.toCollection
如何将返回集合修改为自定义类型的返回集合?
我有一个自定义的 Linkedlist 对象,我想在对其进行某种类型的操作后替换它。
这是我想要实现的一个简单示例:
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。将其修复为列表的当前大小解决了该问题。 谢谢你们!
您可以使用Collector.of
为collect
java 流自定义supplier
:
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
的结果的函数,这个函数在使用并行流处理时是必需的。有关示例的更多详细信息,请参阅此链接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.