Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Array List of String[] arrays

I am reading in a .csv file sort of like a spreadsheet in excel. There are a certain number of columns, determined by the file, and I read each line into a string array using the .split(",") method. I then put this into an array list so it can hold all of the string arrays without giving it a specific size. However, when I go to sort the array list using Collections.sort(), the program breaks. What could the problem be? Here is my code to sort:

Collections.sort(stringList, new Comparator < String[] > () {
    public int compare(String[] strings, String[] otherStrings) {
        return -1 * (strings[sortNum].compareTo(otherStrings[sortNum]));
    }
});
like image 833
nathpilland Avatar asked Sep 06 '11 16:09

nathpilland


People also ask

How do I sort a list of string arrays?

An ArrayList can be sorted by using the sort() method of the Collections class in Java. It accepts an object of ArrayList as a parameter to be sort and returns an ArrayList sorted in the ascending order according to the natural ordering of its elements.

How do you sort an ArrayList of an array?

Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.

How would you sort a list of strings in Java?

Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.

How do I sort nested ArrayList?

To sort an ArrayList in descending order we use reverseOrder() method as an argument of a sort() method. we can't directly call the reverseOrder() method. This method takes two parameters one is an object of ArrayList and the second parameter is the Collections.


1 Answers

Two points:

  • Don't multiply the result of compare by -1 to reverse a comparison. Integer.MIN_VALUE * -1 is still Integer.MIN_VALUE. Instead, reverse the order of the comparison itself
  • My guess is that you've actually got some rows without enough columns. Perhaps you should put those at the end?

Something like:

Collections.sort(stringList, new Comparator < String[] > () {
    public int compare(String[] x1, String[] x2) {
        if (x1.length > sortNum && x2.length > sortNum) {
            return x2[sortNum].compareTo(x1[sortNum]); 
        }
        if (x1.length > sortNum) {
            return 1;
        }
        if (x2.length > sortNum) {
            return -1;
        }
        return x2.length - x1.length;
    }
});

Alternatively, filter your list first to make absolutely sure that all rows have enough columns.

like image 54
Jon Skeet Avatar answered Sep 22 '22 04:09

Jon Skeet