Spróbuj porównawczy, który usuwa wszystkie non-cyfrowy znaki następnie porównuje pozostałe znaki jako liczby:
Collections.sort(strings, new Comparator<String>() {
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}
int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});
Oto test:
public static void main(String[] args) throws IOException {
List<String> strings = Arrays.asList("room1", "foo", "room2", "room100", "room10");
Collections.sort(strings, new Comparator<String>() {
public int compare(String o1, String o2) {
return extractInt(o1) - extractInt(o2);
}
int extractInt(String s) {
String num = s.replaceAll("\\D", "");
// return 0 if no digits found
return num.isEmpty() ? 0 : Integer.parseInt(num);
}
});
System.out.println(strings);
}
wyjściowa:
[foo, room1, room2, room10, room100]
Musisz utworzyć niestandardową comparartor –
wiem, ale nie mam pojęcia jak go porównać. Wiesz, że próbuję z tym: > int int intortyNumbers (String o1, String o2) { Pattern numberPattern = Pattern.compile (WZORZEC); Matcher matcher1 = numberPattern.matcher (o1); Matcher matcher2 = numberPattern.matcher (o2); int i1 = Integer.parseInt (matcher1.group()); int i2 = Integer.parseInt (matcher2.group()); System.out.println (i1 + "" + i2); powrót i1 - i2; } – MAGx2
Należy wprowadzić założenia, takie jak, czy wszystkie ciągi w formacie? lub zdecyduj, jaki dokładnie jest twój format, tylko wtedy możesz napisać swój kompilator. –