Consider I have a library call which accepts:
- a list of items (of mixed/multiple types
T1,T2,T3,..), and - a custom comparator
C,
and, in addition to doing some work, sorts the list it accepts (first by type, and then using the custom comparator C).
Now, I need items of type T1 sorted by type and then using the custom order, while items of all other types (T2, T3,..) sorted by type only (i. e., once sorted by type, consequently sorted only with a no-op, order-preserving comparator).
In other words, I need smth like this (T1 is java.lang.Integer, T2 is java.lang.String):
import java.util.Comparator;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Comparator.comparing;
import static java.util.Comparator.comparingInt;
class C {
/**
* The library call.
*/
static <T> void processAndSort(final List<T> items,
final Comparator<? super T> secondaryComparator) {
final Comparator<T> typeComparator = comparing(it -> it.getClass().getName());
items.sort(typeComparator.thenComparing(secondaryComparator));
// Do some extra work.
}
public static void main(final String ... args) {
final List<?> items = asList(13, "Lorem",
8, "ipsum",
5, "dolor",
3, "sit",
2, "amet",
1, "consectetur",
1, "adipiscing");
processAndSort(items, (final var left, final var right) -> {
final Class<?> clazz = left.getClass();
/*
* Should be already sorted by type.
*/
if (!clazz.equals(right.getClass())) {
throw new IllegalStateException();
}
if (clazz.equals(Integer.class)) {
/*
* Compare integers using a custom comparator.
*/
return comparingInt(Integer::intValue).compare((Integer) left, (Integer) right);
}
/*
* For all other types, retain the original order.
*/
return 0;
});
System.out.println(items);
}
}
The above code, when run, will produce the following output:
[1, 1, 2, 3, 5, 8, 13, Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing]
Now, provided that both Merge Sort and Timsort algorithms (used by the JDK to sort non-primitives) are stable, is it okay for my custom comparator to return 0 for the pairs where the order should be preserved?
Do any other alternatives exist?