I have a problem with sorting strings which include integers. If I use the below code I get sorting like: 1some, 2some, 20some, 21some, 3some, some
However I want it
You need to implement your own Comparator
to do this kind of custom sorting. The default String.compareTo()
method seems to sort numbers before characters. When 0
in 20some
gets compared to s
in 3some
the 0
has a higher sort priority and therefore the whole word gets sorted in first.
What you would need to do is this: try to split you strings into the number and the character part. That's a hard task since those String
s can consist of many of those parts (or don't they?). You may use algorithms like Alphanum
, which Murtaza already showed to you.
If you want to implement it yourself, you could check, where the number part ends. Then parse it to an int
with Integer.parse()
. Compare int
parts if they exist in both String
s, then compare the rest. Well that may not be the most professional solution, but as a beginner you may want craft those things yourself to learn it.
You can't use the default String compareTo() instead need compare the Strings following the below algorithm.
Repeat the steps.
You can do the core of it in one line using regex to extract the numeric part:
Collections.sort(selectedNodes, new Comparator<DefaultMutableTreeNode>() {
@Override
public int compare(DefaultMutableTreeNode o1,
DefaultMutableTreeNode o2) {
return Integer.parseInt(o1.getUserObject().toString().replaceAll("\\D", "")) -
Integer.parseInt(o2.getUserObject().toString().replaceAll("\\D", ""));
}
});
If you know that pattern is always NUMALPHA or ALPHANUM and alpha always same:
if(str1.length() != str2.length()){
return str1.length() - str2.length();
}
return str1.compareTo(str2);
String [] str = new String[]{"1some", "2some", "20some", "21some", "3some", "some"};
List<String> list = Arrays.asList(str);
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
System.out.println(list);