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. 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. I tried to modify IKo's code as follows:
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. In other words, right now the order of all the elements is correct, but the element have been altered which I don't want.
Comparator.comparing(is a number).thenComparing(is capital).thenComparing(natural ordering)Arrays.sort().filterexpects a boolean not a string (which is whatreplaceAllreturns). You probably should be using amaprather than afilter.