Reputation: 525
I have an array of Strings like so:
String[] array = { "CC/2", "DDD/3", "AAAA/4", "B/1" };
Arrays.sort(array);
System.out.println(Arrays.toString(array));
When I execute this code, I get the following:
[AAAA/4, B/1, CC/2, DDD/3]
This is correct, however I want to sort it by the numbered value instead, so that I get the following result:
[B/1, CC/2, DDD/3, AAAA/4]
How do I go about doing this?
Upvotes: 3
Views: 294
Reputation: 22206
Use a custom Comparator
and remove the characters before the numbers, like this:
Arrays.sort(array, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.replaceAll("[A-Z]+/", "").compareTo(o2.replaceAll("[A-Z]+/", ""));
}
});
The .replaceAll("[A-Z]+/", "")
part removes your leading CC/
, AAAA/
, and so on; assuming your strings always start with at least one uppercase letter followed by a slash (/
).
Upvotes: 2
Reputation: 23012
You can do it like this by the use of Comparator<String>
/* You may found some shortcuts for this
but following code is easy to understand
*/
String[] array = { "CC/2", "DDD/3", "AAAA/4", "B/1"};
Arrays.sort(array, new Comparator<String>() {
public int compare(String o1, String o2) {
int i1,i2;
/*
You should add some checks like
1] null check
or
2] whether String contains / or not etc before going for further
code.
*/
/* Get Numbers from String To compare */
i1=Integer.valueOf(o1.split("/")[1]);
i2=Integer.valueOf(o2.split("/")[1]);
//May throw NumberFormatException so be careful with this
if(i1>i2)
return 1;
else if(i1<i2)
return -1;
else
return 0;
}
});
System.out.println(Arrays.toString(array));//Print array
Upvotes: 4
Reputation: 1907
You will have to make your own sorting function. If the numbers will always be at the end of the strings you could reverse the strings using
StringBuilder().reverse().toString()
then you could sort them like you did before and then reverse them back. This will give you give you the strings in order of the numbers, but if you have multiple strings with the same number they will be sorted backwards.
Upvotes: 0
Reputation: 4541
You need a custom Comparator
:
Comparator<String> c = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.split("/")[1].compareTo(s2.split("/")[1]);
}
};
String[] array = { "CC/2", "DDD/3", "AAAA/4", "B/1" };
Arrays.sort(array, c);
System.out.println(Arrays.toString(array));
This prints [B/1, CC/2, DDD/3, AAAA/4]
Upvotes: 2
Reputation: 21
Have a look at sort(T[] a, Comparator c) in Arrays class: http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html
A custom comparator may be what you want
Upvotes: 0