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());
}
}
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()));
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.
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
.
Make your compareTo
method look like:
public int compareTo(MyList o) {
return this.getOrder() - o.getOrder();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.