Java: Sort a String array in a numeric way
I have a String array that contains the following entries:
Array[0]开发者_开发技巧 = "70% Marc"
Array[1] = "50% Marc"
Array[2] = "100% Marc"
Array[3] = "20% Marc"
And I would like to sort this array descending.
When I use Arrays.sort(Array)
then it does sort it descending but the 100% Marc
is at the bottom (because it only looks at the first character to sort it). I want it to be sorted like this:
"100% Marc"
"70% Marc"
"50% Marc"
"20% Marc"
How can I do that?
Write your own CustomStringComparator
and use it with the sort method.
public class CustomStringComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
// extract numeric portion out of the string and convert them to int
// and compare them, roughly something like this
int num1 = Integer.parseInt(str1.substring(0, str1.indexOf("%") - 1));
int num2 = Integer.parseInt(str2.substring(0, str2.indexOf("%") - 1));
return num1 - num2;
}
}
You have to use a custom Comparator. Basically in your method compare()
you will write the logic to order two String
s.
You will need a custom comparator:
import java.util.Comparator;
public class CustomComparator implements Comparator<String>{
@Override
public int compare(String firstString, String secondString) {
int number1 = Integer.parseInt(firstString.substring(0, firstString.indexOf('%') - 1);
int number2 = Integer.parseInt(secondString.substring(0, secondString.indexOf('%') - 1);
return number1.compareTo(number2);
}
}
Use this comparator with something like this:
List<String> entries = new ArrayList<String>();
entries.add("70% Marc");
entries.add("50% Marc");
entries.add("100% Marc");
entries.add("20% Marc");
CustomComparator comparator = new CustomComparator();
Collections.sort(entries, comparator);
It's not looking at the first character, it's sorting based on a string value as that's what you have in your array.
I would suggest storing two fields,
Array[0,0] = 50; Array[0,1] = "Marc"
And then sorting based on the numeric field, if that's the behaviour you're after.
You'd need to implement a custom Comparator<String>
that handles the comparison by removing the percent sign:
public int compare(String str1, String str2) {
Integer number1 = Integer.parseInt(str1.substring(0, str1.length - 1));
Integer number2 = Integer.parseInt(str1.substring(0, str2.length - 1));
return number1.compareTo(number2);
// or use primitives, and then: return (x < y) ? -1 : ((x == y) ? 0 : 1);
// but that's harder to read
}
The comparison itself can be done by using the Integer
wrapper, the code that I pasted (taken from the wrapper), or guava's Ints.compare(int1, int2)
Then use Collections.sort(array, comparator)
精彩评论