Java Collection Compare compareTo(Collection a, Collection b)

Here you can find the source of compareTo(Collection a, Collection b)

Description

compare To

License

LGPL

Declaration

public static <T extends Comparable<T>> int compareTo(Collection<T> a, Collection<T> b) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.util.Collection;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Main {

    public static <T extends Comparable<T>> int compareTo(Collection<T> a, Collection<T> b) {
        int c = a.size() - b.size();
        if (c != 0)
            return c;
        Iterator<T> ia = a.iterator();
        Iterator<T> ib = b.iterator();
        while (ia.hasNext()) {
            c = ia.next().compareTo(ib.next());
            if (c != 0)
                return c;
        }//from ww  w  .  j ava 2 s .c om
        return 0;
    }

    public static <K extends Comparable<K>, V extends Comparable<V>> int compareTo(Map<K, V> a, Map<K, V> b) {
        int c = a.size() - b.size();
        if (c != 0)
            return c;
        Iterator<Entry<K, V>> ia = a.entrySet().iterator();
        Iterator<Entry<K, V>> ib = b.entrySet().iterator();
        while (ia.hasNext()) {
            Entry<K, V> ea = ia.next();
            Entry<K, V> eb = ib.next();
            c = ea.getKey().compareTo(eb.getKey());
            if (c != 0)
                return c;
            c = ea.getValue().compareTo(eb.getValue());
            if (c != 0)
                return c;
        }
        return 0;
    }
}

Related

  1. compareCollections(Collection value1, Collection value2)
  2. compareExactOrder(Collection c1, Collection c2)
  3. compareRef(final Collection left, final Collection right)
  4. compareSet(Collection s1, Collection s2)
  5. compareTo(Collection o1, Collection o2)