簡體   English   中英

Java Streams:使用 Collectors.toCollection 將返回集合修改為自定義類型

[英]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.ofcollect java 流自定義supplier

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的結果的函數,這個函數在使用並行流處理時是必需的。

有關示例的更多詳細信息,請參閱此鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM