I have an ArrayList.
Each element is a HashMap lookup for my values.
1 of the values is numeric.
I’m using Collections.sort() for alpha sorting. But the numbers are getting alpha sorted, instead of numeric sorted.
protected ArrayList<HashMap<String, String>> myAccountList;
String Name = myAccountList.get(i).get("accountName");
Double balance = Double.valueOf(myAccountList.get("accountBalance")); //is a number stored as a string
So I have the sort working on accountName just fine.
Collections.sort(myAccountList, new Comparator(){
public int compare(Object o1, Object o2) {
HashMap<String,String> old1 = (HashMap<String, String>) o1;
HashMap<String,String> old2 = (HashMap<String, String>) o2;
return old1.get("accountName").compareToIgnoreCase(old2.get("accountName"));
}
});
How would I sort the field accountBalance as a number? I doubt it matters, but I’m programming an Android app.
It looks like you’re using a
HashMapwhere you should design your own class:(Note: currently this class is immutable. To make it mutable, change the fields from
public finaltoprivateand add getters/setters)Then you can store them in a
List<Account>and sort accordingly:Note the use of a
Comparatorwith the generic type parameter<Account>, so you don’t have to cast thecompareTo()arguments fromObject.