Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining varargs and generics for chained comparisons in Java

Here's a tough nut to crack. I have a clash between using varargs and generics together. Following given code:

public class MyObject implements Comparable<MyObject>
{
    private String name;
    private int index;

    @Override
    public int compareTo(MyObject o)
    {
        if (name.compareTo(o.name) != 0)
            return name.compareTo(o.name);
        return ((Integer) index).compareTo(o.index);
    }
}

I want the compareTo method to use more than one compare condition. If the strings are the same then use the ints instead. Usual situation I would say.
I would love to create a static method to handle this in general. And I want the new method chainedCompare to be called like this:

public int compareTo(MyObject o)
{
    return chainedCompare(this, o, myO -> myO.name, myO -> myO.index);
}

The lambdas are varargs of the Java 8 interface Function. So first I wrote the method like that:

public static <T, C extends Comparable<C>> int chainedCompare(T object1, T object2, Function<T, C>... comparisons)
{
    int compareValue = 0;
    for (Function<T, C> comparison : comparisons)
    {
        compareValue = comparison.apply(object1).compareTo(comparison.apply(object2));
        if (compareValue != 0)
            break;
    }
    return compareValue;
}

But I didn't consider that in this case the generic type C must be the same type for all Function<T, C> comparisons in the varargs array. As you can see above, I want to use different Comparables (like String and Integer in the example).
Then I modified it to this version:

public static <T> int chainedCompare(T object1, T object2, Function<T, ? extends Comparable<?>>... comparisons)
{
    int compareValue = 0;
    for (Function<T, ? extends Comparable<?>> comparison : comparisons)
    {
        compareValue = comparison.apply(object1).compareTo(comparison.apply(object2));
        if (compareValue != 0)
            break;
    }
    return compareValue;
}

Type C is here replaced with wildcards. While the method call would work now, the method itself does not compile, because of the wildcard typed parameter of compareTo.

So on the one hand I need a fixed generic type (extends Comparable) for the Function interface, but on the other hand I need Function interfaces of different (second) generic types where you usually could set a wildcard. How to resolve this?
My only requirement is that I can call the static method as simple as shown with an undefined number of comparison conditions.


Based on the suggestions of Tunaki I was able to modify the method as follows which can be used like desired:

@SuppressWarnings("raw-types")
public static <T> int chainedCompare(T object1, T object2, Function<T, ? extends Comparable>... comparisons)
{
    return Arrays.stream(comparisons)
        .map(Comparator::comparing)
        .reduce(Comparator::thenComparing)
        .map(c -> c.compare(object1, object2))
        .orElse(0);
}

public int compareTo(MyObject o)
{
    return chainedCompare(this, o, myO -> myO.name, myO -> myO.index);
}
like image 241
Arceus Avatar asked Mar 10 '16 12:03

Arceus


1 Answers

Instead of using a Comparable, it would be easier to use a Comparator:

public static <T> int chainedCompare(T object1, T object2, Comparator<T>... comparators) {
    int compareValue = 0;
    for (Comparator<? super T> comparator : comparators) {
        compareValue = comparator.compare(object1, object2);
        if (compareValue != 0)
            break;
    }
    return compareValue;
}

You could also chain all the comparator together using thenComparing and have

@SafeVarargs
public static <T> int chainedCompare(T object1, T object2, Comparator<T>... comparators) {
    return Arrays.stream(comparators)
                 .reduce(Comparator::thenComparing)
                 .map(c -> c.compare(object1, object2))
                 .orElse(0);
}

Then you can use that by constructing Comparator objects with comparing(keyExtractor) or the primitive specialization comparingInt.

@Override
public int compareTo(MyObject o) {
    return chainedCompare(this, o,
             Comparator.comparing(obj -> obj.name),
             Comparator.comparingInt(obj -> obj.index)
           );
}

With this approach, you can even question the existence of such utility and simply have

@Override
public int compareTo(MyObject o) {
    return Comparator.<MyObject, String> comparing(obj -> obj.name)
                     .thenComparingInt(obj -> obj.index)
                     .compare(this, o);
}
like image 157
Tunaki Avatar answered Nov 02 '22 10:11

Tunaki