Java:以数字方式对字符串数组进行排序

问题描述:

我有一个包含以下条目的字符串数组:

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"

我想对这个数组进行降序排序.当我使用 Arrays.sort(Array) 然后它会降序排序但 100% 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"

我该怎么做?

编写自己的 CustomStringComparator 并与 sort 方法一起使用.

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;

    }
}