'Compare fields from Object to top

i need idea how to do top users by field.

For example I want to do top ten users with the greatest field x, and repeat for y and z:

public class User {

  String userId;
  int x;
  int y;
  int z;

  // constructor

  // methods
}

I know I can do Comparable class like FieldXComparator and later adding users and compare but it can be somehow different to do it better?



Solution 1:[1]

Java 8 added a nice shortcut:

users.sort(Comparator.comparing(User::getX));

Top 10:

users.stream()
    .sorted(Comparator.comparing(User::getX).reversed())
    .limit(10)
    .collect(Collectors.toList());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 OhleC