Java Collection Compare compareCollections(Collection a, Collection b)

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

Description

Items are compared according to iteration order (when comparable).

License

Apache License

Parameter

Parameter Description
a a parameter
b a parameter

Declaration

public static int compareCollections(Collection a, Collection b) 

Method Source Code

//package com.java2s;
/**//ww w .  j  a v  a 2 s  .  c o  m
 * 
 *    Copyright 2017 Florian Erhard
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * 
 */

import java.util.Collection;

import java.util.Iterator;

public class Main {
    /**
     * Items are compared according to iteration order (when comparable).
     * @param a
     * @param b
     * @return
     */
    public static int compareCollections(Collection a, Collection b) {
        Iterator it1 = a.iterator();
        Iterator it2 = b.iterator();

        while (it1.hasNext() && it2.hasNext()) {
            Object o1 = it1.next();
            Object o2 = it2.next();
            int r = tryCompare(o1, o2);
            if (r != 0)
                return r;
        }
        if (it1.hasNext())
            return 1;
        if (it2.hasNext())
            return -1;
        return 0;
    }

    public static int tryCompare(Object o1, Object o2) {
        if (o1 instanceof Comparable && o2 instanceof Comparable)
            return ((Comparable) o1).compareTo(o2);
        return 0;
    }
}

Related

  1. compare(Collection a, Collection b)
  2. compare(Collection lhs, Collection rhs)
  3. compare(final Collection o1, final Collection o2)
  4. compare(final Collection c0, final Collection c1, final Comparator c)
  5. compareAnyOrder(Collection c1, Collection c2)
  6. compareCollections(Collection cola, Collection colb)
  7. compareCollections(Collection value1, Collection value2)
  8. compareExactOrder(Collection c1, Collection c2)
  9. compareRef(final Collection left, final Collection right)