Reputation: 1499
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());
}
}
Upvotes: 0
Views: 994
Reputation: 3372
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.
Upvotes: 2
Reputation: 5025
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()));
Upvotes: 3
Reputation: 702
Make your compareTo
method look like:
public int compareTo(MyList o) {
return this.getOrder() - o.getOrder();
}
Upvotes: 1
Reputation: 140417
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
.
Upvotes: 1