[英]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.