Rasmus Faber
Rasmus Faber

Reputation: 49677

Replicate .NET sort in Java

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?

Upvotes: 0

Views: 101

Answers (1)

Rasmus Faber
Rasmus Faber

Reputation: 49677

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]

Upvotes: 3

Related Questions