英文:
Java: How to sort an ArrayList alphabetically with case insensitive and with any number Strings at the end
问题
以下是翻译好的部分:
我想要将我的ArrayList按字母顺序(不区分大小写)进行排序,但是希望任何数字字符串(例如“1999”)都排在列表的末尾。以以下代码为例:
ArrayList<String> names = new ArrayList<>();
names.add("abby");
names.add("Abigail");
names.add("Dylan");
names.add("becky");
names.add("011");
我要如何使其呈现如下所示:
["abby", "Abigail", "becky", "Dylan", "011"]
我原本想使用以下代码:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
尽管它对ArrayList开头的数字进行了排序。您有关于如何最简单地实现此目标的任何想法吗?谢谢!
英文:
I would like to sort my ArrayList alphabetically (case insensitive) but have any number Strings (e.g. "1999") be at the end of the list. Take the following code for example:
ArrayList<String> names = new ArrayList<>();
names.add("abby");
names.add("Abigail");
names.add("Dylan");
names.add("becky");
names.add("011");
How would I get this to look like:
["abby", "Abigail", "becky", "Dylan", "011"]
I was going to use the following code:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Although it sorts the number at the beginning of the ArrayList. Any ideas on what would be the easiest way to go about this? Thanks!
答案1
得分: 0
Composition
创建自己的字符串比较器 Comparator<String>。首先测试数字,然后使用 String.CASE_INSENSITIVE_ORDER。
public class MyStringComparator implements Comparator<String> {
public int compareTo(String a, String b) {
// 如果 a 和 b 都是数字,或许可以使用 String.CASE_INSENSITIVE_ORDER?
// 如果 a 全是数字,返回 -1
// 如果 b 全是数字,返回 1
return String.CASE_INSENSITIVE_ORDER.compare(a, b);
}
}
英文:
Composition
Create your own Comparator<String>. Test for digits first, then and use String.CASE_INSENSITIVE_ORDER.
public class MyStringComparator implements Comparator<String> {
public int compareTo(String a, String b) {
//if both a and b are digits, maybe use String.CASE_INSENSITIVE_ORDER?
//if a is all digits return -1
//if b is all digits return 1
return String.CASE_INSENSTIVE_ORDER(a,b);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论