java sort arraylist of objects by field descending 1

java sort arraylist of objects by field descending

List sortedUsers = users.stream()
  .sorted(Comparator.comparing(User::getCreatedOn).reversed())
  .collect(Collectors.toList());

Here is what the above code is Doing:
1. We’re using the stream() method on the List to get a Stream of User objects.
2. We’re using the sorted() method on the Stream to sort the User objects by the createdOn field.
3. We’re using the reversed() method on the Comparator to sort the User objects in descending order.
4. We’re using the collect() method on the Stream to collect the sorted User objects into a List.

Similar Posts