简体   繁体   English

如何在Java中对该数组列表进行排序

[英]How do I sort this array list in java

I am using OpenCsv to access a fie which I wish to sort and then write back to another file name. 我正在使用OpenCsv访问要排序的文件,然后写回另一个文件名。 Am having problem sorting the list. 排序列表时遇到问题。 Thanks. 谢谢。

Am trying to sort the csv file by the 1st and 2nd columns. 我正在尝试按第一列和第二列对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();

I am getting the following error when I run this code: 运行此代码时出现以下错误:

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)

Does this help you? 这对您有帮助吗?

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);
        }
    }

It's not clear whether you want the rows sorted within themselves or compared to each other. 目前尚不清楚是要对行进行排序还是将它们进行比较。 Assuming both; 兼而有之;

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.
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM