Hello stackoverflow community!
I am new to these forums and also fairly new to java and android programming–which happen to be the objects of my question–so sorry in advance for any blunders!
My issue is sorting. I am looking for a method to sort objects based on a field that I choose (not sorting based on the first field, then the next, etc. exemplified by comparator chaining). I believe I’ve found the solution to my problem:
https://stackoverflow.com/a/5113108/1549672
but I am having trouble actually getting this to work. I have a suspicion that I’m probably missing something due to my lack of java experience, so any help is welcome!
Here is what I am trying:
As my class-
public class ItemLocation {
String title;
int id;
}
As my function-
public void sort(final String field, List<ItemLocation> itemLocationList) {
Collections.sort(itemLocationList, new Comparator<ItemLocation>() {
@Override
public int compare(ItemLocation o1, ItemLocation o2) {
if(field.equals("title")) {
return o1.title.compareTo(o2.title);
} else if(field.equals("id")) {
return Integer.valueOf(o1.id).compareTo(o2.id);
}
return 0;
}
});
}
using these, could someone possibly give an example of using this method? I attempted to fill an ArrayList and sort it, but to no avail.
Thanks for the help!
You should not return
0from theComparator.comparemethod if they are not equal. It’s “okey” by the contract, but not exactly encouraged, from the API documentation:In my opinion you should return a specific
Comparatorfor each field instead: