简体   繁体   中英

Java Streams: modifying return collection to a custom type with Collectors.toCollection

How can I modify the return collection to that of a custom type?
I have a custom Linkedlist Object that I would like to replace after doing some type of operation on it.

Here's a simple example of what I would like to achieve:

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

I get the following error from this CustomlinkedList::new piece of code.

Bad return type in method reference: cannot convert CustomLinkedList to java.util.Collection

I guess I could just convert it to a default LinkedList Object, iterate over it and add the nodes one by one to my customLinkedList implementation, but that doesnt feel like a clean solution to me.

Here's a link to the customList I am using: customLinkedList
Is there a way to solve this problem?


UPDATE:

Based on Ismail's proposal I managed to get the implementation for Collector.of like so:

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

But now I get the following error:

java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0


SOLUTION:

I completely forgot I was using Spliterators.spliterator with a set size of 0. Fixing that to the current size of the list fixed the issue. Thank you all!

You can customize the supplier for the collect java stream using Collector.of :

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

Collector.of has three parameters:

  1. The supplier to use, in your case CustomLinkedList .
  2. The function of how to add elements to your supplier.
  3. The function that returns the result of two merged different CustomLinkedList list1 and list2 in my example, this function is necessary when using parallel stream processing.

For more details with example see this link .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM