簡體   English   中英

Java Stream sorted() 到通用列表

[英]Java Stream sorted() to generic List

我有一個名為“文章目錄”的列表(通用類型)。

一篇文章有以下方法:

public int getUnitsInStore()
public long getUnitPrice()

現在我想使用 Java Stream sorted() 按單個文章的總值(單位 * pricePerUnit)對這個列表進行排序。

我試過了:

catalog = catalog.stream()
    .map(a -> a.getUnitPrice() * a.getUnitsInStore())
    .sorted((a, b)->a.compareTo(b))
    .collect(Collectors.toCollection(List<Article>::new));

但它給了我以下錯誤:

Cannot instantiate the type List<Article>

我做錯了什么?

編輯:我也試過:

catalog = catalog.stream()
    .map(a -> a.getUnitPrice() * a.getUnitsInStore())
    .sorted((a, b)->b.compareTo(a)).collect(Collectors.toList());

它說:

Type mismatch: cannot convert from List<Long> to List<Article>

你不能做new List() ,所以你不能做List::new 是一個界面。 它不能被實例化。

如果將其更改為ArrayList<Article>::new ,則不會出現該錯誤。

然而

.collect(Collectors.toCollection(ArrayList<Article>::new));

基本上只是使用類型見證的一種更詳細的方式:

.collect(Collectors.<Article>toList());

盡管如此,Java 也應該能夠從分配中推斷出類型。 如果 stream 是Stream<ArticleParent>並且您嘗試分配給List<Article> ,它應該能夠推斷出這一點。 您省略了該字段的聲明,因此我假設您是對的,編譯器由於某種原因無法正確推斷它。

嘗試這個。

catalog = catalog.stream()
    .sorted(Comparator.comparing(a -> a.getUnitPrice() * a.getUnitsInStore()))
    .collect(Collectors.toList());

您也可以按相反的順序排序。

catalog = catalog.stream()
    .sorted(Comparator.comparing((Article a) -> a.getUnitPrice() * a.getUnitsInStore()).reversed())
    .collect(Collectors.toList());

暫無
暫無

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

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