对 Map<String, String> 的 List 进行排序 [英] sorting a List of Map<String, String>
问题描述
我有一个像这样创建的列表变量:
I have a list variable created like this:
List
在我的 Android 应用程序中,此列表被填充.
In my Android application, this list gets populated.
举个例子:
Map<String, String> map1 = new HashMap<String, String>();
map.put("name", "Josh");
...
Map<String, String> map2 = new HashMap<String, String>();
map.put("name", "Anna");
...
Map<String, String> map3 = new HashMap<String, String>();
map.put("name", "Bernie");
...
list.add(map1);
list.add(map2);
list.add(map3);
我使用 list
通过扩展 BaseAdapter
并实现各种方法在 ListView
中显示结果.
I am using list
to show results in a ListView
by extending BaseAdapter
and implementing the various methods.
我的问题:我需要根据地图的键 name
My problem: I need to sort list
in alphabetical order based on the map's key name
问题:根据地图的键 name 按字母顺序对 list
进行排序的简单方法是什么?
Question: What is a simple way to sort list
in alphabetical order based on the map's key name?
我似乎无法理解这一点.我已经将每个 Map
中的每个 name 提取到一个 String
数组中,并对其进行了排序(Arrays.sort(strArray);代码>).但这不会保留每个
Map
中的其他数据,所以我不太确定如何保留其他映射值
I can't seem to wrap my head around this. I have extracted each name from each Map
into a String
array, and sorted it(Arrays.sort(strArray);
). But that doesn't preserve the other data in each Map
, so i'm not too sure how i can preserve the other mapped values
推荐答案
以下代码完美运行
public Comparator<Map<String, String>> mapComparator = new Comparator<Map<String, String>>() {
public int compare(Map<String, String> m1, Map<String, String> m2) {
return m1.get("name").compareTo(m2.get("name"));
}
}
Collections.sort(list, mapComparator);
但您的地图可能应该是特定类的实例.
But your maps should probably be instances of a specific class.
这篇关于对 Map<String, String> 的 List 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!