简体   繁体   中英

Java Stream sorted() to generic List

I have a List called "catalog" of Articles (generic Type).

An Article has following Methods:

public int getUnitsInStore()
public long getUnitPrice()

Now i want to sort this list by the total value of a single Article (units * pricePerUnit) using Java Stream sorted().

I've tried:

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

But its giving me following error:

Cannot instantiate the type List<Article>

What i'm doing wrong?

EDIT: I've also tried:

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

It says:

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

You can't do new List() , so you can't do List::new . It's an interface. It can't be instantiated.

If you were to change it to ArrayList<Article>::new , you wouldn't get that error.

However

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

is basically just a more verbose way of using a type witness:

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

All that said, Java should also be able to infer the type from the assignment. If the stream is Stream<ArticleParent> and you are trying to assign to List<Article> , it should be able to infer that. You've omitted the declaration of the field, so I'll assume that you're right that the compiler cannot infer it correctly for some reason.

Try this.

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

You can also sort in reverse order.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM