基于另一个列表的值对列表进行排序 - Java [英] Sorting a list based on another list's values - Java
问题描述
一个名单列表:(未排序)例如 [paul,foul,mark]
One list with names:(unsorted) e.g [paul, foul, mark]
另一个带整数的列表:例如 [5,2,6]
Another list with integers: e.g [5, 2, 6]
第二个列表中的值是每个人(名称)选中的数字,因此
保罗号码为5号,犯规号码为2号,标记号码为6号。
The values on the second list are the numbers "selected" by each person(name), so paul has number 5, foul's number is 2, mark's number is 6.
我正在尝试根据第二个列表的值对名称列表进行排序降序排列。我不能使用地图,因为我需要在我的程序上的其他场合使用这两个列表。
I'm trying to sort the names' list based on the values of the second list on a descending order. I cant use a map as i need both lists on other occasions on my program.
通过排序方法我做了我得这样的列表: [paul,mark,foul]
With the sorting method i did i get a list like that: [paul, mark, foul]
正如您所看到的,它没有按照我的意愿排序。
As you can see, its not sorted as i would want.
正确一个将是: [标记,保罗,犯规]
但我无法在代码上找到错误。
But i cant find the fault on the code.
public ArrayList<String> sortNames(ArrayList<Integer> results){
String tmp;
for (int k=0; k<Names.size()-1; k++) {
boolean isSorted=true;
for (int i=1; i<Names.size()-k; i++) {
if (results.get(i)>results.get(i-1) ) {
tmp=Names.get(i);
Names.set(i,Names.get(i-1));
Names.set(i-1,tmp);
isSorted=false;
}
}
if (isSorted) break;
}
return Names;
}
编辑!!!在下面的答案的帮助下,代码是:
public ArrayList<String> sortNames(ArrayList<Integer> results){
String tmp2;
int tmp;
for (int k=0; k<Names.size()-1; k++) {
boolean isSorted=true;
for (int i=1; i<Names.size()-k; i++) {
if (results.get(i)>results.get(i-1) ) {
tmp=results.get(i);
results.set(i,results.get(i-1));
results.set(i-1,tmp);
tmp2=Names.get(i);
Names.set(i,Names.get(i-1));
Names.set(i-1,tmp2);
isSorted=false;
}
}
if (isSorted) break;
}
return Names;
}
此代码正常工作(适用于小型列表)
我只是查询为什么它不适用于像ImageIcon这样的对象。任何想法?
This code works properly(for small lists) I've just the query why it doesnt work for objects like ImageIcon. Any ideas?
推荐答案
摆脱两个列表。如果数据是相关的,那么数据应该一起存储在一个简单的类中。然后将整个类添加到列表中,您可以根据需要对各个属性进行排序。您可以使用 Bean Comparator 按照您的意愿对此列表进行排序。
Get rid of the two Lists. If the data is related then the data should be stored together in a simple class. Then the entire class is added to a list where you can sort on the individual properties if required. You can use a Bean Comparator to sort this List however you desire.
这篇关于基于另一个列表的值对列表进行排序 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!