How to compare two maps by their values

前端 未结 13 924
囚心锁ツ
囚心锁ツ 2020-12-08 12:09

How to compare two maps by their values? I have two maps containing equal values and want to compare them by their values. Here is an example:

    Map a = ne         


        
13条回答
  •  独厮守ぢ
    2020-12-08 12:22

    All of these are returning equals. They arent actually doing a comparison, which is useful for sort. This will behave more like a comparator:

    private static final Comparator stringFallbackComparator = new Comparator() {
        public int compare(Object o1, Object o2) {
            if (!(o1 instanceof Comparable))
                o1 = o1.toString();
            if (!(o2 instanceof Comparable))
                o2 = o2.toString();
            return ((Comparable)o1).compareTo(o2);
        }
    };
    
    public int compare(Map m1, Map m2) {
        TreeSet s1 = new TreeSet(stringFallbackComparator); s1.addAll(m1.keySet());
        TreeSet s2 = new TreeSet(stringFallbackComparator); s2.addAll(m2.keySet());
        Iterator i1 = s1.iterator();
        Iterator i2 = s2.iterator();
        int i;
        while (i1.hasNext() && i2.hasNext())
        {
            Object k1 = i1.next();
            Object k2 = i2.next();
            if (0!=(i=stringFallbackComparator.compare(k1, k2)))
                return i;
            if (0!=(i=stringFallbackComparator.compare(m1.get(k1), m2.get(k2))))
                return i;
        }
        if (i1.hasNext())
            return 1;
        if (i2.hasNext())
            return -1;
        return 0;
    }
    

提交回复
热议问题