Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collections.sort is not sorting anything

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:

  • Poecilia Latipinna
  • Poecilia Reticulata
  • Notropis Chrosomus
  • Pseudomugil Gertrudae
  • ....

Whyyyy?

like image 524
Berit Larsen Avatar asked Jan 27 '15 13:01

Berit Larsen


People also ask

Why is Collections sort not working?

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.

What sorting method does Collections sort use?

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.

How do you sort objects in Collections?

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.

What is the complexity of Collections sort?

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


2 Answers

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();
like image 179
jmcg Avatar answered Oct 14 '22 13:10

jmcg


The solution was

Arrays.sort(FishNamesSorted, String.CASE_INSENSITIVE_ORDER)

I had misunderstood how it works

like image 2
Berit Larsen Avatar answered Oct 14 '22 13:10

Berit Larsen