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]));
}
});
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.
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.
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.
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.
Two points:
compare
by -1 to reverse a comparison. Integer.MIN_VALUE * -1
is still Integer.MIN_VALUE
. Instead, reverse the order of the comparison itselfSomething 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With