Hello,
So I have an ArrayList of objects which have information to them like name and a few int values. I wanted to get the top 10 objects of a certain int value. How would I go about doing that?
Printable View
Hello,
So I have an ArrayList of objects which have information to them like name and a few int values. I wanted to get the top 10 objects of a certain int value. How would I go about doing that?
Code:List<YourClass> yourList;
//...
Collections.sort (yourList, new Comparator<YourClass>() {
@Override
public int compare(YourClass o1, YourClass o2) {
return o1.getSomeIntValue () - o2.getSomeIntValue ();
}
});
This is easy if the objects held by the ArrayList implement the Comparable interface. If so, simply call java.util.Arrays.sort(myArrayList), and pick out the top 10. If the objects don't implement Comparable, you'll could do the same but sort with a Comparator object. Google for a tutorial and give it a try.
Much luck!