Java HashMap sorting

3.1k views Asked by At

Possible Duplicate:
Java Ordered Map

I have list of product object in the HashMap<Integer,Product> I want to do the sorting

   ProductName  ProductCode Qty     Price 
   Pen          100011       10     10.00     product1
   Penci        100012        5      5.00     product2

    HashMap<Integer,Product> productMap = new HashMap<Integer,Product>();

When the user click on the ProductName ,productCode or Price, the object should sort according to the my requirements.

 I added like this.
 productMap .put(1,product1);
 productMap .put(2,product2);

How can i do this.I want to sort using the object.not key

Please help me.

Thanks in advance

3

There are 3 answers

0
Petar Ivanov On BEST ANSWER

If you don't want to frequently access the values based on the key, you shouldn't use HashMap. Just use a List of the values and implement different Comparator<Product>s. Then sort the list with the appropriate comparator.

0
aishwarya On

HashMaps are not sorted, you can use TreeMap if you need a sorted map. Alternatively, you could get the keySet, sort it, iterate it and pull information from HashMap, but that would be unnecessary IMHO.

0
SilentBomb On

HashMap map = new HashMap();

hash map is storing the values in the form of key,value pair.and it was not synchronized(means it can act upon many threads).intial capacity of hasmap is 16.and load factor is 0.75. intial capacity*loadfactor=16*0.75=12 that means after storing the 12 th key vale pair hash map size is doubled.

When you use its key and value pair.them these values will be used in unordered way..

You Can also try it(for sorting)------->

public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);

LinkedHashMap sortedMap = 
    new LinkedHashMap();

Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
    Object val = valueIt.next();
    Iterator keyIt = mapKeys.iterator();

    while (keyIt.hasNext()) {
        Object key = keyIt.next();
        String comp1 = passedMap.get(key).toString();
        String comp2 = val.toString();

        if (comp1.equals(comp2)){
            passedMap.remove(key);
            mapKeys.remove(key);
            sortedMap.put((String)key, (Double)val);
            break;
        }

    }

}
return sortedMap;

}