Hello All,
I don't know how often others have to do this, but every once in a while I
have to compare 2 collections and return an int value like the
Comparable.compareTo() contract.

Maybe I'm the only one that wants to do this or I'm implementing the objects
wrong, but I wrote a little utility class to compare 2 collections. Thought
I would share because there doesn't seem to be much out there.

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

* @author James R Perkins (JRP)
* @version 1.0.0
public class CollectionsUtil {
private CollectionsUtil() {


* Compares the first collection against the second collection. Returns
* negative integer, zero or positive integer.
* <p>
* If the size of the first collection is greater than the size of the
* second collection, a positive integer is return. If the size of the
* collection is less than the size of the second collection a negative
* number is returned.
* </p>
* <p>
* If the size of the two collections is equal, then each element from
* collection 1 is compared to the element in the same position from
* collection 2.
* </p>
* @param <T>
* the type of the collection. Both collections must be the
* type and implement {@code java.lang.Comparable}.
* @param c1
* the first collection to be compared
* @param c2
* the second collection to be compared
* @return a negative integer, zero, or a positive integer as the first
* argument is less than, equal to, or greater than the second.
public static <T extends Comparable<? super T>> int compare(
Collection<T> c1, Collection<T> c2) {
int c = c1.size() - c2.size();
List<T> l1 = new ArrayList<T>(c1);
List<T> l2 = new ArrayList<T>(c2);
for (int i = 0; i < l1.size(); i++) {
c = l1.get(i).compareTo(l2.get(i));
if (c != 0) {
return c;

James R. Perkins

As an Amazon Associate we earn from qualifying purchases.

This thread ...


Follow On AppleNews
Return to Archive home page | Return to MIDRANGE.COM home page

This mailing list archive is Copyright 1997-2022 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact [javascript protected email address].

Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.