0

I was trying to sort this ArrayList<Person> in a reverse order but this does not compile

    List<Person> newList = arrayList.stream()
                .sorted(Comparator.reverseOrder(Person::getAge)) //Error
                .limit(3)
                .collect(Collectors.toList());

    newList.forEach(System.out::println);

Is there any other way to sort streams in a reverse order?

5
  • 3
    Comparator.reverseOrder() doesn't expect an argument, that's why your solution doesn't work. Commented Jul 18, 2019 at 13:30
  • 4
    are you trying this in a text editor? if not, there surely is a very descriptive error message from the compiler in the IDE of your choice
    – Eugene
    Commented Jul 18, 2019 at 13:38
  • 2
    sugestão para leitura: Comparator
    – user85421
    Commented Jul 18, 2019 at 14:10
  • 2
    The comment by Eugene is worth being elaborated here: The sequence of sorted(...).limit(3) might have drawbacks. If you have a list of 10000000 elements and want to obtain the top 3 of them, then sorting the 10000000 elements is just a waste of time. There are more elegant solutions for obtaining the "top 'k' elements" when 'k' is much smaller than the size of the input.
    – Marco13
    Commented Jul 18, 2019 at 14:43
  • 1
    Like this
    – Holger
    Commented Jul 18, 2019 at 16:12

1 Answer 1

5

Here is the correct way to use it:

.sorted(Comparator.comparing(Person::getAge).reversed())
2
  • 1
    limit.sorted vs sorted.limit is not the same thing, though.
    – Eugene
    Commented Jul 18, 2019 at 13:36
  • 1
    if you really want to suggest a better solution then using a heap structure with only 3 elements inside it, would be a better choice for large inputs.
    – Eugene
    Commented Jul 18, 2019 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.