简体   繁体   中英

Sorting HashMap using absolute values of doubles

I am attempting to sort a hashmap on type <Integer,Double> using a TreeMap and a SortedMap I want to sort on the absolute values of the Double s but I also want to retain the sign value (hence not storing as an unsigned Double ).

Below is the code I am using, however I am not getting the values I expect, presumably due to the use of hashcode() can anybody point out how to fix this?

Map<Integer,Double> termWeights = new HashMap<Integer,Double>();    
SortedMap sortedData = new TreeMap(new ValueComparer(termWeights));
System.out.println(termWeights);
sortedData.putAll(termWeights);
System.out.println(sortedData);

class ValueComparer implements Comparator {
    private Map _data = null;

    public ValueComparer(Map data) {
        super();
        _data = data;
    }

    public int compare(Object o1, Object o2) {
        Double e1 = Math.abs((Double) _data.get(o1));
        Double e2 = Math.abs((Double) _data.get(o2));
        int compare = e2.compareTo(e1);
        if (compare == 0) {
            Integer a = o1.hashCode();
            Integer b = o2.hashCode();
            return b.compareTo(a);
        }
        return compare;
    }
}

Thanks

Can you give an example of expected and actual results?

Sorted map: {17=1.644955871228835, 0=-1.029545248153297, 10=-5.291765636407169E-4, 9=-3.331976978545177E-4, 1=-2.7105555587851366E-4, 2=-2.7105555587851366E-4, 7=-2.0897436261984377E-4, 8=-1.305197184270594E-5, 3=0.0, 4=0.0, 5=0.0, 6=0.0, 11=0.0, 12=0.0, 13=0.0, 14=0.0, 15=0.0, 16=0.0, 18=0.0, 19=0.0, 20=0.0, 21=0.0, 22=0.0}

So what is the problem?

That looks correctly sorted from biggest to smallest.

But I would avoid using hashCode in the tie-break secondary comparator, because you need it to never return the same value for different inputs. In this case, it works, because you are calling it on an Integer, where hashCode just returns the same int. But if you used Long or String keys in your map, it would have collisions. Compare the two keys directly instead.

And finally, you must not change the weights after starting to use the comparator. That will lead to an inconsistent TreeMap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM