dimanche 28 juin 2015

sorting on map based on values

How to sort a hash map based on values and if the values are same then the sorting should be on the key.

I tried to use a comparator, but its not giving expected results.

I want the result to be like this

results: {Bajaj=8.0, Tata=7.99, Maruthi=6.34, Kmart=5.99, Honda=5.78, Adidas=4.99,Ford=3.99, Nike=3.99, Sears=3.99, Suzuki=3.99, Apple=2.99, Puma=1.99}

public class Test {

public static void main(String[] args) {

    HashMap<String,Double> map = new HashMap<String,Double>();
    ValueComparator bvc =  new ValueComparator(map);
    TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);

    map.put("Adidas",4.99);
    map.put("Nike",3.99);
    map.put("Puma",1.99);
    map.put("Ford",3.99);
    map.put("Apple",2.99);
    map.put("Sears",3.99);
    map.put("Kmart",5.99);
    map.put("Tata",7.99);
    map.put("Maruthi",6.34);
    map.put("Honda",5.78);
    map.put("Bajaj",8.0);
    map.put("Suzuki",3.99);

    System.out.println("unsorted map: "+map);

    sorted_map.putAll(map);

    System.out.println("results: "+sorted_map);
}
}

class ValueComparator implements Comparator<String> {

Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
    this.base = base;
}

// Note: this comparator imposes orderings that are inconsistent with equals.    
public int compare(String a, String b) {
    if (base.get(a) > base.get(b)) {
        return -1;
    } 
    else if(base.get(a) == base.get(b))
    {
        System.out.println();
        if(a.compareTo(b) == -1)
        {

            return -1;
        }
        else if(a.compareTo(b) == 1)
        {

        return 1;
        }
        else
        {

            return 0;
        }
    }
    else {
        return 1;
    } // returning 0 would merge keys
}
}

Aucun commentaire:

Enregistrer un commentaire