对包含带数字的字符串的 Arraylist 进行排序 [英] Sorting an Arraylist that contains strings with numbers

查看:36
本文介绍了对包含带数字的字符串的 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.

这篇关于对包含带数字的字符串的 Arraylist 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆