It appears that the task is about sorting the pairs of elements of the input array (however, all elements are Comparable
) and it can be resolved without creating/using Pair
class with the help of Stream API.
Also, the output result is also an array of objects.
Object[] values = { "Cat", 4, "Bat", 4, "Dat", 6, "Bat", 2 };
// prepare comparators
Comparator<List<Comparable>> comparator0 = Comparator.comparing(list -> list.get(0));
Comparator<List<Comparable>> comparator1 = Comparator.comparing(list -> list.get(1));
Object[] sorted = IntStream.range(0, values.length / 2)
.mapToObj(i -> Arrays.asList((Comparable)values[2 * i], (Comparable)values[2 * i + 1]))
.sorted(comparator0.thenComparing(comparator1))
.flatMap(List::stream)
.toArray(Object[]::new);
System.out.println(Arrays.toString(values));
System.out.println(Arrays.toString(sorted));
Output:
[Cat, 4, Bat, 4, Dat, 6, Bat, 2]
[Bat, 2, Bat, 4, Cat, 4, Dat, 6]
.sorted
may use Comparator
written in this equivalent form:
sorted((a1, a2) -> a1.get(0).compareTo(a2.get(0)) == 0
? a1.get(1).compareTo(a2.get(1))
: a1.get(0).compareTo(a2.get(0))
)