Java: How to sort an ArrayList alphabetically with case insensitive and with any number Strings at the end

huangapple go评论78阅读模式
英文:

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&lt;String&gt; names = new ArrayList&lt;&gt;();
names.add(&quot;abby&quot;);
names.add(&quot;Abigail&quot;);
names.add(&quot;Dylan&quot;);
names.add(&quot;becky&quot;);
names.add(&quot;011&quot;);

How would I get this to look like:

[&quot;abby&quot;, &quot;Abigail&quot;, &quot;becky&quot;, &quot;Dylan&quot;, &quot;011&quot;]

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&lt;String&gt; {
  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&lt;String>. Test for digits first, then and use String.CASE_INSENSITIVE_ORDER.

public class MyStringComparator implements Comparator&lt;String&gt; {
  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);
  }
}

huangapple
  • 本文由 发表于 2020年4月6日 23:29:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/61063290.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定