简体   繁体   English

对字母数字字符串列表进行排序:java

[英]Sort a list of alphanumeric strings: java

I have string lists我有字符串列表

String[] list = ...

where the elements contain alphanumeric characters only.其中元素仅包含字母数字字符。 What I want to do is sort each element of the list such that numbers come first, then the alphabet of capital letters, and then the alphabet of lower case letters.我想要做的是对列表中的每个元素进行排序,使数字先出现,然后是大写字母的字母表,然后是小写字母的字母表。

For example, with input list例如,使用输入列表

u78t
U78
7u8
X92

the output would be输出将是

7u8
U78
X92
u78t

I have been trying to find the right approach, and I have been reading about Comparators, but it is a bit overwhelming and at minimum I'd like to know if they are even what I should be looking at to try to accomplish my goal.我一直在努力寻找正确的方法,并且我一直在阅读关于比较器的文章,但这有点让人不知所措,至少我想知道它们是否是我实现目标时应该考虑的内容。

Thanks!谢谢!

EDIT: IKo's answer works perfectly.编辑:IKo 的回答完美无缺。 However, I should have asked to allow non-alphanumeric characters in the strings.但是,我应该要求在字符串中允许非字母数字字符。 There will be at least one alphanumeric character in each string, and any non-alphanumerics should be ignored when sorting (but kept).每个字符串中至少有一个字母数字字符,排序时应忽略任何非字母数字字符(但保留)。

For example, with input例如,输入

&Bd
*$8

The return should be回报应该是

*$8
&Bd

Because non-alphanumerics get ignored (but kept) and numbers come before (captial) letters.因为非字母数字被忽略(但保留)并且数字出现在(大写)字母之前。 However, IKo's code produces the reverse order.但是,IKo 的代码产生相反的顺序。 I tried to modify IKo's code as follows :我尝试修改 IKo 的代码如下

private String[] sort(String[] input) {
        return Arrays.stream(input)
                .map(s -> s.replaceAll("[^a-zA-Z0-9]", ""))
                .sorted()
                .toArray(String[]::new);
    }

which is meant remove non-numeric while sorting, but this seems to be the wrong approach, I thought replaceAll would remove non-alphanumerics only when sorting, but the output itself has had non-alphanumerics removed.这意味着在排序时删除非数字,但这似乎是错误的方法,我认为 replaceAll 只会在排序时删除非字母数字,但输出本身已删除了非字母数字。 In other words, right now the order of all the elements is correct, but the element have been altered which I don't want.换句话说,现在所有元素的顺序是正确的,但元素已被更改,这是我不想要的。

You can use something like this:你可以使用这样的东西:

private String[] sort(String[] input) {
        return Arrays.stream(input)
                .sorted()
                .toArray(String[]::new);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM