Suppose that I have a list of strings 'ABC123'
, 'XXY111'
, 'EFG001
' and so on.
I need to sort these strings in 2 ways,
1) First sorted by the numbers.
2) Then it sorted by the letters.
I tried using a Comparator to sort the strings.
First I split the string and had the numbers at the beginning and then sorted the List using Collections.sort()
.
But I am not sure how to sort it in the two ways.
Below is my code,
public class SortAlphaNumeric {
static class MyComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
String oo1 = o1.substring(3) + o1.substring(0,3);
String oo2 = o2.substring(3) + o2.substring(0,3);
return oo1.compareTo(oo2);
}
}
public static void main(String[] args) {
String str1 = "ABC123";
String str2 = "ACB111";
String str3 = "XXX003";
String str4 = "XYZ001";
String str5 = "CDE123";
String str6 = "FEG111";
List<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
list.add(str4);
list.add(str5);
list.add(str6);
System.out.println("Before sorting");
Iterator<String> itr1 = list.iterator();
while(itr1.hasNext()) {
System.out.println(itr1.next());
}
SortAlphaNumeric.MyComparator myComp = new SortAlphaNumeric.MyComparator();
System.out.println("========================");
Collections.sort(list, myComp);
System.out.println("After 1st sorting");
Iterator<String> itr2 = list.iterator();
while(itr2.hasNext()) {
System.out.println(itr2.next());
}
Collections.sort(list, myComp);
System.out.println("After 2nd sorting");
Iterator<String> itr3 = list.iterator();
while(itr3.hasNext()) {
System.out.println(itr3.next());
}
}
}