Java Comparator.comparing not comparing?

You can make a list of pairs :

[3.0, 5.0]
[1.0, 0.9]
[2.0, 10.4]

Then sort this list of pairs by the first value of each array :

[1.0, 0.9]
[2.0, 10.4]
[3.0, 5.0]

Here is the code :

List<Double> nums = Arrays.asList(5.0, 0.9, 10.4);
List<Double> order = Arrays.asList(3.0, 1.0, 2.0);

List<Double[]> pairs = new ArrayList<>();
for (int i = 0; i < nums.size(); i++) {
    pairs.add(new Double[] {order.get(i), nums.get(i)});
}

pairs.sort(Comparator.comparing(pair -> pair[0]));

for (Double[] pair : pairs) {
    System.out.print(pair[1] + " ");
}

Output :

0.9 10.4 5.0 

You are sorting the numbers by their position in the order list, but none of the numbers occur in the order list. In this case, indexOf will return -1 for everything, meaning everything is equal to everything else. In such a case, the resulting sort order is unspecified - though you may realistically assume that it would not change.

Tags:

Java

Sorting