This question already has an answer here:
- Sort ArrayList of custom Objects by property 25 answers
I have a list of point objects, which I want to sort by a certain coordinate, say the x-values. Does Java provide any useful mechanisms or should I avail myself of one of the common sort algorithms?
Yes create a custom
Comparator
, and use it to sort list of pointsIn
Point
class you should implement Comparable interface with generic type<Point>
and useCollections.sort
(java.util package) for sortingList<Point>
Assume:
You should either make your point class to implement Comparable interface or provide sort() method with your own Comparator object, which tells sort() how to order your objects. There a lot of examples around here.
You can use something like a Bean Comparator so you don't have to keep creating custom Comparators.