Does somebody knows how to order an array with words with special characters like accents?
Arrays.sort(anArray);
returns 'Albacete'
before 'Álava'
, and I want 'Álava'
before 'Albacete'
.
Thanks a lot
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
The main logic is to toCharArray() method of the String class over the input string to create a character array for the input string. Now use Arrays. sort(char c[]) method to sort character array. Use the String class constructor to create a sorted string from a char array.
Using the sort() Method In Java, Arrays is the class defined in the java. util package that provides sort() method to sort an array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting.
The java. util. Arrays. sort(char[]) method sorts the specified array of chars into ascending numerical order.
If you just want to sort the strings as if they didn't have the accents, you could use the following:
Collections.sort(strs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
o1 = Normalizer.normalize(o1, Normalizer.Form.NFD);
o2 = Normalizer.normalize(o2, Normalizer.Form.NFD);
return o1.compareTo(o2);
}
});
Related question:
For more sophisticated use cases you will want to read up on java.text.Collator
. Here's an example:
Collections.sort(strs, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
Collator usCollator = Collator.getInstance(Locale.US);
return usCollator.compare(o1, o2);
}
});
If none of the predefined collation rules meet your needs, you can try using the java.text.RuleBasedCollator
.
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