Reputation: 3102
I have a list of HashMaps. Each HashMap consists of several kay-value pairs and everything comes as a string. I am storing all the hashmaps inside an arraylist. Now I need to sort the arraylist based on the key inside the hashmap.
Here is my sample data:
{
"productID":"5643",
"productName":"Apple - iPod touch",
"outsidePrice":"189.99",
"merchantID":"134439",
"ourPrice":"184.99",
"storeName":"Ebay",
}
{
"productID":"3243",
"productName":"Apple - iPad",
"outsidePrice":"389.99",
"merchantID":"54439",
"ourPrice":"384.99",
"storeName":"Apple",
}
I am storing this data inside this structure.
ArrayList<HashMap<String, String>> data_list = new ArrayList<HashMap<String, String>>();
I have a huge list of items like this. Now I need to sort the arraylist based on the productName, Price, storeName, productID fields inside the hashmap.
Upvotes: 4
Views: 12558
Reputation: 14472
I recommend that you use a custom product class to do this for you. It will ultimately make your code easier to maintain and more robust, IMHO.
How about this?
A class to represent your data:
class Product{
public string productId;
public string productName;
public BigDecimal outsidePrice;
public int merchantId;
public BigDecimal ourPrice;
public string storeName;
// whatever constuctors you need
}
A List of your products:
List<Product> products;
Now define a Comparator to sort, one for each field that you need to sort on. Here is an example for productId.
public class ProductProductIdComparator implements Comparator<Product>{
@Override
public int compare(Product product1, Product product2) {
if (product1.productId > product2.productId){
return +1;
}else if (product1.productId < product2.productId){
return -1;
}else{
return 0;
}
}
}
And finally, a Collections sort which accepts a comparator as an argument:
Collections.sort(products, new ProductProductIdComparator());
Upvotes: 7
Reputation: 80633
The Collections class provides a utility method for sorting a list in place, using a Comparator.
final List<Map<String, String>> dataList = new ArrayList<HashMap<String, String>>(4);
Collections.sort(dataList, new Comparator<Map<String, String>>() {
@Override
public int compare(final Map<String, String> map1, final Map<String, String> map2) {
// Get fields from maps, compare
}
}
Upvotes: 6
Reputation: 4421
You can use arrays.sort() to achieve this in short, at some minor memory cost.
HashMap[] result = Arrays.sort(list.toArray(), new Comparator() {
public void compare(Object o1, Object o2) {
HashMap<String, String> a = (HashMap<String, String>)o1;
HashMap<String, String> b = (HashMap<String, String>)o2;
// return value as per contract of Comparator.compare() doing whatever comparisons you need.
}
public boolean equals(Object obj) { return this == obj; }
});
Upvotes: -1