我有一个ArrayList<HashMap<String,String>>
.
有没有办法改变 HashMaps 数组的顺序?例如,如果字符串“firstName”在 HashMap 中,我可以按该值对 HashMap 的 ArrayList 进行排序吗?为了清楚起见,我不需要在 HashMaps 中对键和对象进行排序。我需要在 Arraylist 中订购 HashMaps。
什么是最好的方法?
我试着从例子做:
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);
}
}
并使用:
Log.e(THIS_FILE, "before ->" + addedRows);
Collections.sort(addedRows, new MapComparator("name"));
Log.e(THIS_FILE, "after ->" + addedRows);
并且没有任何排序(确保我将一个联系人重命名为以字母 a 开头,名称 = as ice:) 的哈希图必须是第一个):
> 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=дима куплеватскиц}]