-2

Hi I'm very new to this so I have no idea how to figure this out after thinking for couple days, I have a question regarding the sorting of Objects inside of an ArrayList. I have a single ArrayList that contains Objects. Each Object has a double "distance". I want to sort my Objects within the ArrayList based on the smallest distance.

I been struggling on this one for a while now since I suck with sorting :( If anyone can help me out I would appreciate it, and let me know if I'm being to vague, not sure how to explain it.

Var_Matt1
  • 19
  • 5
  • 4
    possible duplicate of [Sorting a collection of objects](http://stackoverflow.com/questions/1206073/sorting-a-collection-of-objects). See also: [Sorting an ArrayList of Contacts based on name?](http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts-based-on-name?lq=1) and [Sort ArrayList of custom Objects by property](http://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property). – Paul Bellora Jun 13 '13 at 00:47
  • Typing in the title gives you numerous relevant "questions that may already have your answer". OP did not put in too much effort here... – Zong Jun 13 '13 at 00:54
  • I did search but couldn't understand most of them, I'm very new to programming :( – Var_Matt1 Jun 13 '13 at 01:14
  • @Riven Then unfortunately you probably did not understand the answer you chose, but it just works. Please take a look at the other answers so you understand why. Becoming better at programming is not just about having code that works. – Zong Jun 13 '13 at 01:34
  • @ Zong Zheng Li I understood the answer I chose, what I meant was I didn't understand the Collections class when I was searching for a solution to this, but now I mostly understand it. – Var_Matt1 Jun 13 '13 at 22:28

2 Answers2

2

I think a slight improvement on the previous answer is box into a Double then use compareTo

Collections.sort(list, new Comparator<MyObject>() {
    public int compare(MyObject o1, MyObject o2) {
        return new Double(o1.getDistance()).compareTo(o2.getDistance());
    }
});

If you want to sort largest first then change to

return new Double(o2.getDistance()).compareTo(o1.getDistance());
sparkdoo
  • 522
  • 1
  • 5
  • 13
1

First, it's good to provide accessors for the distance property in the class you have.

Then, in order to sort the list based on the distance field of the objects within, you can use an anonymous implementation of the Comparator interface.

List<MyObject> list = ...;
Collections.sort(list, new Comparator<MyObject>() {
    public int compare(MyObject o1, MyObject o2) {
        if (o1.getDistance() == o2.getDistance()) { 
             return 0;
        } else { 
           return o1.getDistance() > o2.getDistance() ? 1 : -1;
        }
    }
});
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147