Reputation: 5854
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.
Upvotes: 4
Views: 10908
Reputation: 890
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...
Upvotes: 1
Reputation: 3610
Can be done using comparator and Collections class together if its a case of ArrayList
Check this link
Thanks to Lars vogel
Upvotes: 1
Reputation: 31222
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?
Upvotes: 7
Reputation: 2073
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
Upvotes: 2
Reputation: 14520
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;
}
});
Upvotes: 18