Sorting Alphanumeric List in Using Comparator Interface
public class AlphaNumericComparators<T> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
String obj1 = null;
String obj2 = null;
try {
if (null == o1 || null == o2) {
return 1;
}
obj1 = (String) o1;
obj2 = (String) o2;
BigDecimal val1 = new BigDecimal(obj1);
BigDecimal val2 = new BigDecimal(obj2);
return val1.compareTo(val2);
} catch (Exception e) {
return obj1.compareTo(obj2);
}
}
}
public class Test {
public static void main(String[] args) {
List<Object> list = new ArrayList<Object>();
list.add("50000");
list.add("xxxa");
list.add("10");
list.add("12");
list.add("Abvs");
list.add("6");
list.add("sdsdsd");
list.add("-1");
list.add(null);
System.out.println("Before Sorting");
System.out.println(list);
Collections.sort(list, new AlphaNumericComparators<Object>());
System.out.println("After Sorting");
System.out.println(list);
}
}
Output
Before Sorting
[50000, xxxa, 10, 12, Abvs, 6, sdsdsd, -1, null]
After Sorting
[-1, 6, 10, 12, 50000, Abvs, sdsdsd, xxxa, null]
public class AlphaNumericComparators<T> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
String obj1 = null;
String obj2 = null;
try {
if (null == o1 || null == o2) {
return 1;
}
obj1 = (String) o1;
obj2 = (String) o2;
BigDecimal val1 = new BigDecimal(obj1);
BigDecimal val2 = new BigDecimal(obj2);
return val1.compareTo(val2);
} catch (Exception e) {
return obj1.compareTo(obj2);
}
}
}
public class Test {
public static void main(String[] args) {
List<Object> list = new ArrayList<Object>();
list.add("50000");
list.add("xxxa");
list.add("10");
list.add("12");
list.add("Abvs");
list.add("6");
list.add("sdsdsd");
list.add("-1");
list.add(null);
System.out.println("Before Sorting");
System.out.println(list);
Collections.sort(list, new AlphaNumericComparators<Object>());
System.out.println("After Sorting");
System.out.println(list);
}
}
Output
Before Sorting
[50000, xxxa, 10, 12, Abvs, 6, sdsdsd, -1, null]
After Sorting
[-1, 6, 10, 12, 50000, Abvs, sdsdsd, xxxa, null]
No comments:
Post a Comment