我正在使用OpenCsv访问我希望排序的fie,然后写回另一个文件名。我有问题排序列表。谢谢。
我试图按第1列和第2列对csv文件进行排序。
CSVReader reader = new CSVReader(new FileReader("d:\\temp\\data1.csv"), ',', '"', 1);
//Read all rows at once
List<String[]> allRows = reader.readAll();
//Read CSV line by line and use the string array as you want
for(String[] row : allRows){
System.out.println(Arrays.toString(row));
}
*Arrays.sort(allRows.toArray());*
CSVWriter writer = new CSVWriter(new FileWriter("d:\\temp\\data1sorted.csv"));
writer.writeAll(allRows);
//close the writer
writer.close();
运行此代码时出现以下错误:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.String; cannot be cast to java.lang.Comparable
at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.ComparableTimSort.sort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at CompareCsv.main(CompareCsv.java:31)
答案 0 :(得分:1)
这对你有帮助吗?
public static void main(String args[]) {
ArrayList<String> animalList = new ArrayList<String>();
animalList.add("Dog");
animalList.add("Cat");
animalList.add("Snake");
animalList.add("Bison");
System.out.println("Before Sorting:");
for (String tmpStr : animalList) {
System.out.println(tmpStr);
}
// sorting
Collections.sort(animalList);
System.out.println("After Sorting:");
for (String tmpStr : animalList) {
System.out.println(tmpStr);
}
}
答案 1 :(得分:0)
您可以为您的目的实施比较器并使用: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)
答案 2 :(得分:0)
目前尚不清楚您是希望行内排序还是相互比较。 假设两者;
for(String[] row : allRows)
{
Arrays.sort(row);
}
Collections.sort(allRows, new Comparator()
{
@Override
public int compare(Object o1, Object o2)
{
String[] a = (String[])o1;
String[] b = (String[])o2;
return a[0].compareTo(b[0]); //you'll probably want some additional checking here.
}
});