对包含带数字的字符串的 Arraylist 进行排序
我有一个由字符串组成的 ArrayList.这个 ArrayList 包含...
I have an ArrayList made up of strings. This ArrayList contains...
60 分钟"《120分钟》30 分钟"
"60 Minutes" "120 Minutes" "30 Minutes"
如果我使用 Collections.sort(ArrayList);
它首先会导致120 分钟".这是因为120"中的1"明显小于30"中的3"
If I use Collections.sort(ArrayList);
it results in "120 Minutes" first. This is because the "1" in "120 is obviously smaller than the "3" in "30"
有没有一种简单的方法可以对这个 ArrayList 进行排序,使其显示为...
Is there a simple way I can sort this ArrayList so that it shows up as...
30 分钟"《60分钟》《120 分钟》
"30 Minutes" "60 Minutes" "120 Minutes"
定义您自己的类来实现 Comparator
.在 compare
方法中,从字符串参数的第一部分中提取数字并进行比较,如果第一个数字小于、等于或大于,则返回 -1、0 或 1比,第二个数字.
Define your own class that implements Comparator<String>
. In the compare
method, extract the numbers out of the first part of the string arguments and compare them, returning -1, 0, or 1, if the first number is less than, equal to, or greater than, the second number.
然后您可以将比较器的实例(连同您的 ArrayList
)传递给 Collections.sort
.
Then you can pass an instance of your comparator (along with your ArrayList
) to Collections.sort
.