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?
Comparator.reverseOrder()
doesn't expect an argument, that's why your solution doesn't work.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.