Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting ArrayList of HashMap based on key value

Tags:

java

hashmap

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.

like image 882
intrepidkarthi Avatar asked Dec 15 '22 17:12

intrepidkarthi


2 Answers

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());
like image 130
Simon Avatar answered Dec 31 '22 14:12

Simon


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
    }
}
like image 32
Perception Avatar answered Dec 31 '22 16:12

Perception