java Android:如何订购 ArrayList<HashMap<String,String>>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12137518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: How to Order ArrayList<HashMap<String,String>>?
提问by Pattabi Raman
I'm saving details of product in a map and adding in ArrayList< HashMap< String,String >> and setting in to a custom list adapter. I need to sort the values by price in it. How to achieve it? Thanks in advance.
我将产品的详细信息保存在地图中并添加到 ArrayList< HashMap< String,String >> 并设置为自定义列表适配器。我需要按其中的价格对值进行排序。如何实现?提前致谢。
回答by Eldhose M Babu
Pleas use the code below :
请使用以下代码:
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;
}
});
回答by prayagupd
You can implement a Comparator<Map<String, String>>
or Comparator<HashMap<String, String>>
您可以实施一个Comparator<Map<String, String>>
或Comparator<HashMap<String, String>>
How sort an ArrayList of HashMaps holding several key-value pairs each?answers it well :
如何对每个包含多个键值对的 HashMap 的 ArrayList 进行排序?回答得很好:
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"));
Also look at How to sort a Map on the values in Java?
回答by Anuj
you can simply use this for your custom Sorting of objects in an Array List,
您可以简单地将其用于自定义数组列表中的对象排序,
public class MyComparator implements Comparator<MyObject> {
@Override
public int compare(MyObject o1, MyObject o2) {
return o1.getYOUROBJ1STR.compareTo(o2.getYOUROBJ2STR);
}
}
Let me know if you still face issues for sorting of Map
如果您仍然面临 Map 排序问题,请告诉我
回答by Zoombie
回答by Hunter
I think you are searching for this:-
我想你正在寻找这个:-
Sort ArrayList of custom Objects by property
sorting a List of Map<String, String>
Hope it will helps you...
希望它会帮助你...