I have an ArrayList<HashMap<String,String>>
.
Is there a way to change the order of the array of HashMaps? For example, if the String "firstName" is inside the HashMap, can I sort my ArrayList of HashMaps by that value? Just to be clear, I do not need to order keys and objects inside HashMaps. I need order HashMaps inside Arraylist.
What is a best way?
i tried to do from examples:
class MapComparator implements Comparator<HashMap<String, String>>
{
private final String key;
public MapComparator(String key)
{
this.key = key;
}
public int compare(HashMap<String, String> first,
HashMap<String, String> second)
{
// TODO: Null checking, both for maps and values
String firstName1 = first.get(key);
String firstName2 = second.get(key);
if(firstName1 == null)
if(firstName2 == null)
return 0;
else
return -1; // treat null as less than any non-null
else
if(firstName2 == null)
return 1; // treat null as less than any non-null
else
return firstName1.compareTo(firstName2);
}
}
and using:
Log.e(THIS_FILE, "before ->" + addedRows);
Collections.sort(addedRows, new MapComparator("name"));
Log.e(THIS_FILE, "after ->" + addedRows);
and nothing sorted (to be sure i renamed one contact to start by letter a, hashmap with name=as ice:) must be first):
> E/ContactsActivity(23571): before ->[{type=, contactID=4, name=Office
> O}, {type=, contactID=2912, name=Test Text Last}, {type=,
> contactID=2915, name=as ife:) Eng}, {type=, contactID=2914,
> name=life:) Rus}, {type=, contactID=2913, name=life:) Ukr}, {type=,
> contactID=2897, name=дима куплеватскиц}] E/ContactsActivity(23571):
> after ->[{type=, contactID=4, name=Office O}, {type=, contactID=2912,
> name=Test Text Last}, {type=, contactID=2915, name=as ife:) Eng},
> {type=, contactID=2914, name=life:) Rus}, {type=, contactID=2913,
> name=life:) Ukr}, {type=, contactID=2897, name=дима куплеватскиц}]