[Solved, feel free to use as a resource] Organizing An ArrayList<AnyObjectHere>

Discussion in 'Plugin Development' started by Ahniolator, Oct 12, 2011.

Thread Status:
Not open for further replies.
  1. Offline

    Ahniolator

    I have a list of objects that have a method called getVal() which returns an Integer of roughly between 1-25. Is there a way to organize the list so that the ones with the largest getVal() are at the top and the lowest at the bottom? And furthermore, if the list contains more than 5 or so objects, only get the top 5?

    I may have figured it out, give me a minute -Nope Yup, I got it. For those who are curious:

    Create a class that implements Comparator<YourObjectYouWantToOrganize>:
    Code:java
    1. import java.util.Comparator;
    2.  
    3. public class MyObjectComparator implements Comparator<MyObject> {
    4.  
    5. public int compare(MyObject o1, MyObject o2) {
    6. //This returns negative (in reverse order) for the needs of my plugin. If you want ascending order, just make it positive.
    7. return -o1.getVal().compareTo(o2.getVal());
    8. }
    9. }


    Then call it somewhere in your code like this:

    Code:java
    1. Collections.sort(myArrayList, new MyObjectComparator());


    Theoretically, this should work with any list, but don't quote me on that.
     
    Don Redhorse likes this.
Thread Status:
Not open for further replies.

Share This Page