findAllByOrderByTi" /> findAllByOrderByTi" /> findAllByOrderByTi"/>

Using Collator with Ukrainian language

610 Views Asked by At

Please look at my method where I try to implement Collator to sort Objects with a "title" field. Method:

public List<SchoolSubject> findAllByOrderByTitle() {
    List<SchoolSubject> schoolSubjects = subjectRepository.findAllByOrderByTitle();

    Collator uaCollator = Collator.getInstance(new Locale("ua", "UA"));
    uaCollator.setStrength(Collator.SECONDARY);
    schoolSubjects.stream().sorted((s1, s2)->uaCollator.compare(s1.getTitle(), s2.getTitle()));
    return schoolSubjects;
}

It sorts, but not correctly. Letter "i" is put at the very beginning. Whats wrong with it?

2

There are 2 best solutions below

1
Emil Hotkowski On

I think that you should use new Locale("uk", "UA")

Check this site about Internationalization

EDIT:

I think that problem is with the way Ukrainian Alphabet is represented.

https://en.wikipedia.org/wiki/Ukrainian_alphabet#Unicode

According to Wikipedia, 'i' is the lastest letter considering Unicodes. So maybe you sort in descending order instead of ascending?

0
Dmytro Manzhula On

Correct code:

public List<SchoolSubject> findAllByOrderByTitle() {
    List<SchoolSubject> schoolSubjects = subjectRepository.findAllByOrderByTitle();

    Collator uaCollator = Collator.getInstance(new Locale("uk", "UA"));
    uaCollator.setStrength(Collator.PRIMARY);
    schoolSubjects.sort((s1, s2)->uaCollator.compare(s1.getTitle(), s2.getTitle()));
    return schoolSubjects;
}

Fixed with new Locale("uk", "UA"), excluded stream() from lambda and it sorted correctly.