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.
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());
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With