Java流排序()到泛型列表

Java流排序()到泛型列表,java,sorting,java-stream,Java,Sorting,Java Stream,我有一个名为“一般类型文章目录”的列表 文章有以下几种方法: public int getUnitsInStore() public long getUnitPrice() 现在,我想使用Java Stream sorted按单个项目units*pricePerUnit的总值对该列表进行排序 我试过: catalog = catalog.stream() .map(a -> a.getUnitPrice() * a.getUnitsInStore()) .sorted((

我有一个名为“一般类型文章目录”的列表

文章有以下几种方法:

public int getUnitsInStore()
public long getUnitPrice()
现在,我想使用Java Stream sorted按单个项目units*pricePerUnit的总值对该列表进行排序

我试过:

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

Type mismatch: cannot convert from List<Long> to List<Article>
您无法创建新列表,因此无法创建列表::新建。这是一个界面。它不能被实例化

如果将其更改为ArrayList::new,则不会出现该错误

然而

.collect(Collectors.toCollection(ArrayList<Article>::new));
基本上只是使用类型见证的更详细的方式:

.collect(Collectors.<Article>toList());
尽管如此,Java还应该能够从赋值中推断类型。如果流是stream,并且您正试图分配给List,那么它应该能够推断出这一点。您省略了字段的声明,因此我假设您是对的,编译器由于某种原因无法正确推断它。

试试这个

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());

这给了我一个错误:method CollectorMichael,我相信您在OPs问题中缺少步骤中使用的映射和方法签名,这是导致他们共享错误变体的原因。谢谢,这解决了我的问题。你能告诉我怎样把它倒过来分类吗?最有价值first@Vlad更新了我的答案。非常感谢。我真的很感激
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());