Either you make Player implementing Comparable
and use Collections.sort(players)
or you can directly create a comparator like this
Collections.sort(players, new Comparator<Player>() {
public int compare(Player o1, Player o2) {
return o2.getX().compareTo(o1.getX());
}
});
Assuming player.getX()
returns a Integer
Edit
Let's say you have your List<Player>
named otherPlayers
if you want to sort it directly without writing yourself a loop and the algorithm of sorting, you can rely on the Java built-in method Collections.sort()
to sort it. But this means that either your class Person
implements the Comparable
interface, or you can pass an instance of Comparator
as the second argument of the Collections.sort()
method as done above.
The Comparator.compare()
method takes two object and does return an integer that says if the first argument is lower than the second, equals or greater. This is how the sorting algorithm will know how to order the elements in your list. So, by creating a Comparator
instance that compare the result of Player.getX()
of two Player
instances (the elements of your list), you are able to sort the original list on the position criteria as you asked for it.