我有列表列表(列表行包含列表列)。我想按长度(.size())对ListRZS中的行进行排序。
[[123, 189, 277], [11], [145, 211, 299], [156, 222, 310], [167, 233, 255], [189, 266], [200, 277], [211, 288], [245, 299], [233], [244]]
Shoul be:
[[11], [233], [244], [189, 266],[200, 277], [211, 288], [245, 299], [123, 189, 277], [145, 211, 299], [156, 222, 310], [167, 233, 255]]
问题:如何编写工作组件/可比较这种情况。
public class Start {
public static void main(String[] args) {
System.out.println("Start reading from Xls");
ReaderXls1Column read = new ReaderXls1Column();
ReaderXls readrzs = new ReaderXls();
List<String> listASU = new ArrayList<String>(read.ReaderXls1Column("Text1obj",0,1)); // Creating Lists
List<List<String>> listRZS = new ArrayList<List<String>>(readrzs.ReadXls("Text1obj",2,12));
System.out.println(listASU);
System.out.println(listRZS);
System.out.println("Reading is over");
System.out.println(listRZS);
WriterXls.main("Text1obj",listRZS);
System.out.println("Writing is over");
}
我没有比较器的尝试,可比(当然,不能正常工作)
int k=0;
while ( k<listRZS.size()){
for (int j=0;j<10;j++) {
List<String> tmplist = new ArrayList<String>();
if (listRZS.get(k).size()>listRZS.get(k+1).size()) {Collections.copy(listRZS.get(k),tmplist); listRZS.remove(k); listRZS.add(k+1,tmplist);}
else {};
}
Collections.sort(listRZS.get(k)); // sort each row, solution above
k++;
}
答案 0 :(得分:2)
comparator只需要实现一个方法(compare
),它接受两个项目并返回:
排序整数值时,实现此目的的典型模式是将compare
方法中收到的每个对象减少为整数,然后,如果我们将它们称为a
和b
,只需返回a - b
。
示例(请参阅ideone.com/rcmDbi处运行):
import java.util.*;
class Test {
public static void main(String[] args) {
List<Integer> a = Arrays.asList(1);
List<Integer> b = Arrays.asList(1,2);
List<Integer> c = Arrays.asList(1,2,3);
List<Integer> d = Arrays.asList(1,2,3,4);
List<List<Integer>> test = Arrays.asList(d,b,c,a);
Collections.sort(test, ListSizeComparator.INSTANCE);
for (List<Integer> list : test) {
System.out.println(list.size());
}
}
enum ListSizeComparator implements Comparator<List> {
INSTANCE;
public int compare(List one, List other) {
return one.size() - other.size();
}
}
}
(顺便说一句,我使用了enum singleton pattern的枚举,因为我们的比较器没有存储状态。)
答案 1 :(得分:1)
试试这样:
List<List<String>> myList; // load myList with values
然后按如下方式进行排序:
Collections.sort(myList, new Comparator<List<String>>(){
@Override
public int compare(List<String> arg0, List<String> arg1) {
return arg1.size() - arg0.size();
}
});