[英]Sorting one array based on another using comparator not working
I want to sort one array based on another array in java.我想根据java中的另一个数组对一个数组进行排序。 I can do using Pair data structure but using directly another array in comparator not working.
我可以使用 Pair 数据结构,但直接在比较器中使用另一个数组不起作用。
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final int[] l = new int[]{9, 17, 39, 35, 20, 18, 34, 11, 2, 45, 46, 15, 33, 47, 10, 27};
final List<Integer> n = Arrays.asList(32, 39, 86, 81, 64, 53, 76, 40, 46, 63, 88, 56, 52, 50, 22, 38);
Collections.sort(n, new Comparator<Integer>() {
public int compare(Integer left, Integer right) {
//System.out.println(n.indexOf(left) + " "+n.indexOf(right));
return l[n.indexOf(left)]-l[n.indexOf(right)];
}
});
//Collections.sort(l);
System.out.println(n);
System.out.println(l);
}
}
Getting output - [50, 88, 63, 81, 38, 86, 39, 32, 76, 56, 64, 53, 40, 52, 46, 22] Expected output - [46,32 and so on ] corresponding to [2,9 and so on]获取输出 - [50, 88, 63, 81, 38, 86, 39, 32, 76, 56, 64, 53, 40, 52, 46, 22] 预期输出 - [46,32 等] 对应于 [ 2,9 等]
Your problem is that the reference order changes as you sort the list.您的问题是当您对列表进行排序时,参考顺序会发生变化。 You start with
9->32
and 17->39
for the first two elements.对于前两个元素,您从
9->32
和17->39
开始。 After comparing and changing the first two elements the "mapping" could change and you would have 9->39
and 17->32
instead for the next iteration.在比较和更改前两个元素后,“映射”可能会发生变化,您将在下一次迭代中使用
9->39
和17->32
。
To solve that you need to create a copy of the list.要解决这个问题,您需要创建列表的副本。 Then, while sorting
n
you refer to that copy for the order.然后,在对
n
进行排序时,您可以参考该订单的副本。 Something like this should work:这样的事情应该工作:
public static void main (String[] args) throws java.lang.Exception
{
final int[] l = new int[]{9, 17, 39, 35, 20, 18, 34, 11, 2, 45, 46, 15, 33, 47, 10, 27};
final List<Integer> n = Arrays.asList(32, 39, 86, 81, 64, 53, 76, 40, 46, 63, 88, 56, 52, 50, 22, 38);
List<Integer> listCopy = new ArrayList(n);
Collections.sort(n, new Comparator<Integer>() {
public int compare(Integer left, Integer right) {
return l[listCopy.indexOf(left)]-l[listCopy.indexOf(right)]; \\notice the listCopy.indexOf()
}
});
System.out.println(n);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.