I'm trying to sort a String array in a short, simple way. I'm trying to use Collections.sort, but I don't understand why it doesn't sort anything. Code:
public static String[] FishNamesSorted;
.....
List<String> nameslist = new ArrayList<String>();
nameslist.toArray(FishNamesSorted);
Collections.sort(nameslist, String.CASE_INSENSITIVE_ORDER); <--- NOT WORKING
Collections.sort(nameslist, new Comparator<String>() { <--- NOT WORKING
@Override
public int compare(String p1, String p2) {
if (p1 == null) {
return 1;
}
if (p2 == null) {
return -1;
}
return p1.compareToIgnoreCase(p2);
}
});
Results in both cases:
Whyyyy?
The problem must be with the Strings being used as Keys, which are both causing the TreeMap not to sort and the Collection. sort not to work.
the current Java versions use TimSort. This applies to both, Arrays. sort and Collections. sort, though with Java 8, the List itself may override the sort algorithms.
sort() method is present in java. util. Collections class. It is used to sort the elements present in the specified list of Collection in ascending order.
The time complexity of Collections. sort() is O(n*log(n)) and a list sorted with Collections. sort() will only be sorted after the call to sort(). The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist).
Collections.sort(list)
definitely works. The problem in your code is you placed the list into the array before sorting. The array should be sorted if you sort your list first before putting it to the array
List<String> nameslist = new ArrayList<String>();
/* add elements to namesList */
Collections.sort(nameslist);
Object[] fishNamesSorted = nameslist.toArray();
The solution was
Arrays.sort(FishNamesSorted, String.CASE_INSENSITIVE_ORDER)
I had misunderstood how it works
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