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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:44:43  来源:igfitidea点击:

Android: How to Order ArrayList<HashMap<String,String>>?

javaandroidarraylist

提问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?

另请参阅如何根据 Java 中的值对 Map 进行排序?

回答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

Can be done using comparator and Collections class together if its a case of ArrayList

如果是 ArrayList 的情况,可以一起使用比较器和 Collections 类来完成

Check this link

检查此链接

Thanks to Lars vogel

感谢 Lars vogel

回答by Hunter