4

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.

Pattabi Raman
  • 5,814
  • 10
  • 39
  • 60
  • try googling for map sorting. – d1e Aug 27 '12 at 07:09
  • possible duplicate of [How sort an ArrayList of HashMaps holding several key-value pairs each?](http://stackoverflow.com/questions/5369573/how-sort-an-arraylist-of-hashmaps-holding-several-key-value-pairs-each) – Joachim Sauer Aug 27 '12 at 07:32

5 Answers5

18

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;
        }
    });
Eldhose M Babu
  • 14,382
  • 8
  • 39
  • 44
7

You can implement a Comparator<Map<String, String>> or Comparator<HashMap<String, String>>

How sort an ArrayList of HashMaps holding several key-value pairs each? answers it well :

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?

Community
  • 1
  • 1
prayagupa
  • 30,204
  • 14
  • 155
  • 192
2

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

Anuj
  • 2,065
  • 22
  • 23
1

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

Check this link

Thanks to Lars vogel

Zoombie
  • 3,590
  • 5
  • 33
  • 40
1

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...

Community
  • 1
  • 1
Hunter
  • 820
  • 8
  • 19