简体   繁体   中英

Trying to sort a map where the value is an object and I can sort by multiple values in the object

I'm trying to sort a map based on different possible values in the Student object. This doesn't seem to be working for me and I can't seem to figure out why. Any help would be very appreciated. Thanks!

protected static Map<Integer, Student> sort(Map<Integer, Student> unsorterMap, String field)
{
    Comparator<Integer> valueComparator =  
            new Comparator<Integer>() 
            {
                public int compare(Integer k1, Integer k2) 
                {
                    int compare;
                    if(field.equalsIgnoreCase("name"))
                    {
                        compare = unsorterMap.get(k1).getName().compareTo(unsorterMap.get(k2).getName());
                    }
                    else
                    {
                        compare = Integer.compare(unsorterMap.get(k1).getIndex(), unsorterMap.get(k2).getIndex());
                    }


                    if (compare == 0)
                        return 1;
                    else
                        return compare;
                }
            };

    Map<Integer, Student> sortedMap = new TreeMap <Integer, Student>(valueComparator);
    sortedMap.putAll(unsorterMap);
    return sortedMap;
}

Your comparator violates the Comparator contract. From javadoc :

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y

But in your code, you have

if (compare == 0)
    return 1;
else
    return compare;

If two students have the same value for the field you use to do the comparison, both compare(x,y) and compare(y,x) will return 1.

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