Following this question about sorting a list by another list, I tried to do the same thing - but from some reason it doesn't work for me. What am I missing?
List<Double> nums = Arrays.asList(5.0, 0.9, 10.4);
List<Double> order = Arrays.asList(3.0, 1.0, 2.0);
nums.sort(Comparator.comparing(order::indexOf));
System.out.println(nums);
OUTPUT: [5.0, 0.9, 10.4]
It should be [0.9, 10.4, 5.0] (according to order
). What am I not doing right?
EDIT: As most of you noticed, I got answer to the question I linked to all wrong. Here's what I actually want to do.
Comparable vs Comparator. Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting. For using Comparable, Class needs to implement it whereas for using Comparator we don't need to make any change in the class.
While Comparable is used on objects that are naturally ordered, the Comparator interface implements sorting by taking the attributes of an object into consideration. Further, Comparator sorting takes into account objects of two different classes and Comparable compares objects using the “this” reference.
The compare MethodIt returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.
compareTo(b) : Comparable interface : Compares values and returns an int which tells if the values compare less than, equal, or greater than. compare(a, b) : Comparator interface : Compares values of two objects.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With