我在地图中保存产品的详细信息并添加到ArrayList<的HashMap<字符串,字符串>>并设置自定义列表适配器。我需要按价格对价值进行排序。怎么实现呢?提前谢谢。
答案 0 :(得分:18)
请使用以下代码:
ArrayList< HashMap< String,String >> arrayList=populateArrayList();
Collections.sort(arrayList, new Comparator<HashMap< String,String >>() {
@Override
public int compare(HashMap<String, String> lhs,
HashMap<String, String> rhs) {
// Do your comparison logic here and retrn accordingly.
return 0;
}
});
答案 1 :(得分:7)
您可以实施Comparator<Map<String, String>>
或Comparator<HashMap<String, String>>
How sort an ArrayList of HashMaps holding several key-value pairs each? 很好地回答:
class MapComparator implements Comparator<Map<String, String>>{
private final String key;
public MapComparator(String key){
this.key = key;
}
public int compare(Map<String, String> first,
Map<String, String> second){
// TODO: Null checking, both for maps and values
String firstValue = first.get(key);
String secondValue = second.get(key);
return firstValue.compareTo(secondValue);
}
}
...
Collections.sort(arrayListHashMap, new MapComparator("value"));
答案 2 :(得分:2)
您只需将其用于自定义数组列表中对象的排序,
public class MyComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getYOUROBJ1STR.compareTo(o2.getYOUROBJ2STR);
}
}
如果您仍然面临排序地图
的问题,请与我们联系答案 3 :(得分:1)
答案 4 :(得分:1)
我想你正在寻找: -
Sort ArrayList of custom Objects by property
sorting a List of Map<String, String>
希望它会帮助你......