Java Stream sorted() to generic List



我有一个名为"目录";文章(通用类型(。

文章有以下方法:

public int getUnitsInStore()
public long getUnitPrice()

现在,我想使用JavaStream sorted((根据单个文章的总值(units*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<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());

相关内容

最新更新