我有一个包含以下条目的String数组:

Array[0] = "70% Marc"
Array[1] = "50% Marc"
Array[2] = "100% Marc"
Array[3] = "20% Marc"

我想对这个数组降序排序。
当我使用Arrays.sort(Array)时,它会对其进行降序排序,但100% Marc在底部(因为它只看第一个字符对其进行排序)。我希望将其排序为:
"100% Marc"
"70% Marc"
"50% Marc"
"20% Marc"

我怎样才能做到这一点?

最佳答案

编写自己的CustomStringComparator并将其与sort方法一起使用。

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;

    }
}

07-27 13:27