Java:使用indexOf方法对基于另一个数组的数组进行排序 [英] Java: Sorting an array based on another array with indexOf method
问题描述
我想根据另一个数组(索引)的排序顺序遍历两个数组(A,B),在这种情况下为10、34、32、21。
I want to iterate through two arrays(A, B) based on the sorted order of another array(indexes), which is 10, 34, 32, 21 in this case.
String[] A: a, b, c, d
String[] B: e, f, g, h
int[] indexes: 10, 34, 32, 21
在这里为不好的例子道歉。我已经更新了索引数组,以消除混乱。
Apology for the bad example here. I have updated the indexes array to clear the confusion.
预期的输入和输出
输入是三个数组。我想使用索引数组的排序遍历A,B。也就是说,我想找到一种使用顺序(a,d,c,b)迭代A并使用顺序(e,h,g,f)迭代B的方法
The input are the three arrays. I wanted to iterate through A, B using the sorted of the indexes array. i.e. I want to find a way to iterate A using the order (a, d, c, b) and iterate B using the order (e, h, g, f)
我的方法:
我用一种我认为与另一种方法相同的解决方案解决了这个问题。但是,第二种方法不起作用。如果有人能解释为什么它不起作用,我将不胜感激,因为我认为这可以使我更好地理解Collections.sort在Java中的工作方式。
I solved the problem with a solution that I believe is identical to another approach. However, the second approach does not work. I would appreciate if someone can explain why it does not work as I think it would give me a better understanding of how Collections.sort works in java.
List<Integer> indexOrder = new ArrayList<>(indexes.length);
for (int i = 0; i < indexes.length; i++) {
indexOrder.add(i);
}
Collections.sort(indexOrder, Comparator.comparing((Integer s) -> indexes[s]));
受,我创建了一个值为(1、2、3 ... indexes.length)的ArrayList(最好是AList,而不是数组),然后进行排序它使用带有参考的比较器。索引。 上面的代码按预期工作。
但是,如果我在末尾更改了索引[s] , indexes [indexOrder.indexOf(s)] 的最后一行。排序将给出错误的结果。如果ArrayList的索引与其值相同,为什么indexOf(s)的结果与s不同。
However, if I change the indexes[s] at the end of the last line to indexes[indexOrder.indexOf(s)]. The sorting will give a wrong result. Why is indexOf(s) giving a different result than s if the ArrayList's index is the same as its value.
Collections.sort(indexOrder, Comparator.comparing((Integer s) -> indexes[indexOrder.indexOf(s)]));
推荐答案
似乎您期望 indexOrder .indexOf(s)
始终等于 s
(因为您的列表
已初始化到 [0,1,2,3]
,其中 s
的索引是 s
)。
It seems you expect indexOrder.indexOf(s)
to always be equal to s
(since your List
was initialized to [0, 1, 2, 3]
, where the index of s
is s
).
在原始 indexOrder
列表
中,这是正确的,当 Collections.sort
开始交换 List
的元素时,情况可能不再正确。
While this is true in your original indexOrder
List
, this may no longer true when Collections.sort
starts swapping elements of your List
.
为了在排序时不依赖 indexOrder
的顺序,可以创建该的副本列表
:
In order not to rely on the ordering of indexOrder
while you are sorting it, you can create a copy of that List
:
List<Integer> copy = new ArrayList<>(indexOrder);
Collections.sort(indexOrder, Comparator.comparing((Integer s) -> indexes[copy.indexOf(s)]));
这篇关于Java:使用indexOf方法对基于另一个数组的数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!