Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering an array with special characters like accents

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

like image 403
JLLMNCHR Avatar asked Oct 17 '14 08:10

JLLMNCHR


People also ask

How do you put an array in alphabetical order?

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.

Can we sort character array?

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.

Can you order an array in Java?

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.

Can we sort character array in Java?

The java. util. Arrays. sort(char[]) method sorts the specified array of chars into ascending numerical order.


1 Answers

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:

  • Remove diacritical marks (ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ) from Unicode chars

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.

like image 138
aioobe Avatar answered Oct 20 '22 00:10

aioobe