Sort ArrayList containing numbers and letters

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

Sort ArrayList<String> containing numbers and letters

问题

我有一个包含'建筑关键字'数字列表的ArrayList<String>。如果这已经在之前得到了回答,请原谅我,我通过搜索难以找到解决方案。

public class SortKeyNumbers {
    
    public static void main(String args[]) {
        
        ArrayList<String> keys = new ArrayList<>();
        
        keys.add("1");
        keys.add("10");
        keys.add("2");
        keys.add("3");
        keys.add("3B");
        keys.add("12");
        keys.add("12C");
        keys.add("21");
        keys.add("32");
        
        Collections.sort(keys);
        
        System.out.println(keys);
        
    }
    
}

这给我一个输出 [1, 10, 12, 12C, 2, 21, 3, 32,3B]
我知道这是从 Collections.sort 期望的结果。
我需要的是 [1, 2, 3, 3B, 10, 12, 12C, 21, 32] 的输出。

我要求的是帮助编写正确的 comparatorcompareTo 来实现期望的输出。

英文:

I have an ArrayList&lt;String&gt; containing a list of 'Building Key' numbers.
Forgive me if this has been answered before I am struggling to find a solution by searching.

public class SortKeyNumbers {
    
    public static void main(String args[]) {
        
        ArrayList&lt;String&gt; keys = new ArrayList&lt;&gt;();
        
        keys.add(&quot;1&quot;);
        keys.add(&quot;10&quot;);
        keys.add(&quot;2&quot;);
        keys.add(&quot;3&quot;);
        keys.add(&quot;3B&quot;);
        keys.add(&quot;12&quot;);
        keys.add(&quot;12C&quot;);
        keys.add(&quot;21&quot;);
        keys.add(&quot;32&quot;);
        
        Collections.sort(keys);
        
        System.out.println(keys);
        
    }
    
}

This gives me an output of [1, 10, 12, 12C, 2, 21, 3, 32,3B]
I know that this is as expected from Collections.sort
What I need is an output of [1, 2, 3, 3B, 10, 12, 12C, 21, 32]

What I am asking is help to write the correct comparator or compareTo to achieve the desired output.

答案1

得分: 0

可以使用一个比较器函数,该函数会将键中的任何非数字字符删除,然后将其解析为整数:

Collections.sort(keys, Comparator.comparing(s -> Integer.parseInt(s.replaceAll("[^\\d]", ""))));

输出:

[1, 2, 3, 3B, 10, 12, 12C, 21, 32]
英文:

You can use a comparator function which strips any non-digit characters out of the key and then parses it to an integer:

Collections.sort(keys, Comparator.comparing(s -&gt; Integer.parseInt(s.replaceAll(&quot;[^\\d]&quot;, &quot;&quot;))));

Output:

[1, 2, 3, 3B, 10, 12, 12C, 21, 32]

答案2

得分: 0

你可以使用ArrayList.sort,只需通过移除非数字字符来比较整数。

keys.sort(Comparator.comparing(str -> Integer.valueOf(str.replaceAll("\\D+", ""))));
英文:

You can use ArrayList.sort and just compare only integers by removing non digits

keys.sort(Comparator.comparing(str-&gt; Integer.valueOf(str.replaceAll(&quot;\\D+&quot;,&quot;&quot;))));

huangapple
  • 本文由 发表于 2020年8月24日 10:37:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63554031.html
匿名

发表评论

匿名网友

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

确定