我有一个定义如下的ArrayList:
ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
每张地图中只有一个元素company
,这是公司的名称。我的问题是我如何按字母顺序排列ArrayList。我正在使用它,因为后面的行(在其他视图中)将有更多的元素到HashMap。
答案 0 :(得分:1)
您可以使用Collections.sort()按字典顺序对其进行排序,但是您可以使用Comparator使对象具有可比性
class CmpHashMap implements Comparator<HashMap<String,String>>
{
public int compare(HashMap<String,String> h1,HashMap<String,String> h2)//assuming second String as company name and key as "key"
{
return h1.get("key").compareTo(h2.get("key"));
}
}
然后使用集合
Collections.sort(recalllist,new CmpHashMap());
答案 1 :(得分:1)
使用以下内容:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class MainClass {
public static void main(String[] args) {
ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashMap;
hashMap = new HashMap<String, String>();
hashMap.put("company", "a");
recallList.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("company", "c");
recallList.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("company", "b");
recallList.add(hashMap);
System.out.println(recallList);
Collections.sort(recallList, new Comparator<HashMap<String, String>>() {
@Override
public int compare(HashMap<String, String> hashMap1, HashMap<String, String> hashMap2) {
return hashMap1.get("company").compareTo(hashMap2.get("company"));
}
});
System.out.println(recallList);
}
}
第一和第二输出是:
[{company=a}, {company=c}, {company=b}]
[{company=a}, {company=b}, {company=c}]