Traditional Spanish sorting of Strings in Java

2019-09-09 02:50发布

问题:

I'm converting a .NET application into Java. The app reads in a file with this format:

es-MX
jueves
verde
amarillo
blanco
llave
llover
loma
cinco
domingo
rojo

but I'm having a trouble figuring out how to sort Spanish according to the traditional sorting of words. In VB.NET, you'd do see this:

 Dim spainCultureTraditional As CultureInfo = New CultureInfo(&H40A)

but I can't find the equivalent traditional sorting locale in Java. The only difference between the two is that in es-MX/es-ES llave and llover would be switched versus the international sorting.

Note: the locale es-ES is not necessarily the same in Java and it is not the same in VB.NET.

回答1:

You might need customised Collation rules. There is a demo for tranditional Spanish here:

https://docs.oracle.com/javase/tutorial/i18n/text/rule.html

Summary code:

String smallnTilde = "\u00F1";
String capitalNTilde = "\u00D1";

String traditionalSpanishRules = (
    "< a,A < b,B < c,C " +
    "< ch, cH, Ch, CH " +
    "< d,D < e,E < f,F " +
    "< g,G < h,H < i,I < j,J < k,K < l,L " +
    "< ll, lL, Ll, LL " +
    "< m,M < n,N " +
    "< " + smallnTilde + "," + capitalNTilde + " " +
    "< o,O < p,P < q,Q < r,R " +
    "< s,S < t,T < u,U < v,V < w,W < x,X " +
    "< y,Y < z,Z");

RuleBasedCollator spCollator = new RuleBasedCollator(traditionalSpanishRules);

Collections.sort(words, spCollator);
System.out.println(words);