Is there a Comparator<List<T>> or Comparator<Collection<T>>?

242 Views Asked by At

I am searching for a class that implements one of the following

java.util.Comparator<int[]>
java.util.Comparator<List<T>>
java.util.Comparator<Collection<T>>

Why is there no such class in the Java Standard Library / Apache Common / Google Guava ?

2

There are 2 best solutions below

0
On BEST ANSWER

Guava's Ordering class provides lexicographical ordering of Iterables that uses a base Ordering to compare each pair of elements.

Ordering<T> elementOrdering = ...
Ordering<Iterable<T>> lexicographical = elementOrdering.lexicographical();
1
On

Apache Commons Collections has a ComparatorChain that could be what you are looking for.

But implementing a lexicographical comparator is not so hard either:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class LexicographicalComparatorsTest
{
    public static void main(String[] args)
    {
        List<List<String>> lists = new ArrayList<List<String>>();
        lists.add(Arrays.asList("A", "B", "4"));
        lists.add(Arrays.asList("A", "B", "1"));
        lists.add(Arrays.asList("A", "B", "3"));
        lists.add(Arrays.asList("A", "B", "2"));
        lists.add(Arrays.asList("A", "A", "9"));
        lists.add(Arrays.asList("A", "C", "0"));

        Comparator<String> c = comparableComparator();
        Comparator<List<String>> cc = createCompatator(c);

        Collections.sort(lists, cc);
        for (List<String> list : lists)
        {
            System.out.println(list);
        }
    }

    private static <T extends Comparable<T>> Comparator<T> comparableComparator()
    {
        return new Comparator<T>()
        {
            @Override
            public int compare(T t0, T t1)
            {
                return t0.compareTo(t1);
            }
        };
    }

    public static <T> Comparator<List<T>> createCompatator(
        final Comparator<T> comparator)
    {
        return new Comparator<List<T>>()
        {
            @Override
            public int compare(List<T> list0, List<T> list1)
            {
                int n = Math.min(list0.size(), list1.size());
                for (int i=0; i<n; i++)
                {
                    T t0 = list0.get(i);
                    T t1 = list1.get(i);
                    int result = comparator.compare(t0, t1);
                    if (result != 0)
                    {
                        return result;
                    }
                }
                return 0;
            }
        };
    }
}

A colexicographical comparator can be implemented by reversing the list traversal direction.

The comparator in this example could also be generalized to a Comparator<Collection<T>>, by using manual traversal with two Iterator<T> instances obtained from the collections.