sorted in stream is not applicable

  • A+
Category:Languages

I have this piece of Java8 code:

Set<Purchase> purchases =      user.getAcquisitions()         .parallelStream()         .map(a -> a.getPurchases())     .sorted(Comparator.comparing(Purchase::getPurchaseDate).reversed()); 

But I have this compilation error and I don't know why:

The method sorted(Comparator<? super Set<Purchase>>) in the type Stream<Set<Purchase>> is not applicable for the arguments   (Comparator<Purchase>) 

 


To expand upon Joe's answer, it seems like you want a Set<Purchase> in sorted order (for whatever reason that may be), given you have a good reason to do so in which case you can use a LinkedHashSet:

user.getAcquisitions()     .parallelStream()     .flatMap(e -> e.getPurchase().stream())     .sorted(Comparator.comparing(Purchase::getPurchaseDate).reversed())     .collect(toCollection(LinkedHashSet::new)); 
  • flatMap flattens the nested Set<Purchase> into a Stream<Purchase>
  • it then sorts the elements according to the provided comparator
  • then collects the elements into a LinkedHashSet implementation which respects insertion order.

btw note that you could as well just do:

user.getAcquisitions()     .parallelStream()     .flatMap(e -> e.getPurchase().stream())     .distinct()     .sorted(Comparator.comparing(Purchase::getPurchaseDate).reversed())     .collect(toCollection(ArrayList::new)); 

so, depending on the context you're using the resulting elements you might be better off collecting to a list implementation.

  • flatMap flattens the nested Set<Purchase> into a Stream<Purchase>
  • distinct returns a new stream of the unique objects according to the equals method.
  • it then sorts the elements according to the provided comparator
  • finally, it then collects the element from the stream into an ArrayList implementation.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: