0

I would like to replicate the following simple method in Java:

string[] a = {"u1=1","u2=2","u11=3"};
Array.Sort(a);
Console.WriteLine(String.Join(" ", a));

Output:

u1=1 u11=3 u2=2

The naive Java translation of this uses another String comparison:

String[] a = {"u1=1", "u2=2", "u11=3"};
Arrays.sort(a);
System.out.println(Arrays.toString(a));

Output:

[u11=3, u1=1, u2=2]

I realize that the .NET String.Compare() method depends on localization settings on the machine, but how can I reproduce the .NET sort in a standard English locale using Java?

Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189

1 Answers1

3

This should work:

String[] a = {"u1=1", "u2=2", "u11=3"};
Arrays.sort(a, Collator.getInstance(Locale.ENGLISH));
System.out.println(Arrays.toString(a));

Output:

[u1=1, u11=3, u2=2]

Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189
  • Of cource I figured the answer out on my own 4 minutes after having posted the question. The related question [Linguistic sorting (German) with Java](http://stackoverflow.com/questions/12778841/linguistic-sorting-german-with-java?rq=1) helped me out by pointing me to the Collator class. – Rasmus Faber Jul 14 '13 at 19:12