0

My list

ArrayList<MyList> list = new ArrayList<MyList>();
 //        name    - order - info
list.add("Book ...", "1", "blah blah);
list.add("Book ...", "10", "blah blah);
list.add("Book ...", "11", "blah blah);
list.add("Book ...", "2", "blah blah);

I want to sort the list according to its position in the 2 second obj

Then I tried

Collections.sort(list);

List Calss

public class MyList implements Comparable<MyList> {

...

    @Override
    public int compareTo(@NonNull MyList content) {
        return Integer.parseInt(content.getOrder());
    }
}
0

4 Answers 4

3

You can pass a Comparator object to the sort method.

Collections.sort(list, new Comparator<MyList>() {
    @Override
    public int compare(MyList m1, MyList m2) {
        return m1.getOrder() - m2.getOrder();
    }
});

If you're using java 8 you could do this.

Collections.sort(list, (MyList m1, MyList m2) -> 
                                   m1.getOrder() - m2.getOrder()));
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! This way you can do different Comparisons in different circumstances! Sweet!
2
ArrayList<MyList> list = new ArrayList<MyList>();
     //        name    - order - info
    list.add("Book ...", "1", "blah blah);
    list.add("Book ...", "10", "blah blah);
    list.add("Book ...", "11", "blah blah);
    list.add("Book ...", "2", "blah blah);

    Collections.sort(list, new Comparator<MyList>() {
        @Override
        public int compare(MyList m1, MyList m2) {
            return m1.getOrder() - m2.getOrder();
        }
    });

now check your list is in ascending order.

Comments

1

You need a Comparator here.

That one compares two items, and returns -1, 0, or 1; if the first entry is smaller, equal, bigger than the second one.

But you should go one step further: it seems like you try to model certain data - then don't use a flat MyList list class. Create a class that really models your data; maybe a BookRecord; that has fields like String name, or int id.

Comments

1

Make your compareTo method look like:

    public int compareTo(MyList o) {
        return this.getOrder() - o.getOrder();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.