I know this could be done by using the sort method from Collections class, but my experience is only on one column sort, but I'm not sure whether the sort method is smart enough to handle my requirement. My logic thinking shows that if Column A is sorted, then I further sort on column B. In the same time I was thinking to write a custom bubble sort to cater for this requirement, but it was already late night. Without further thinking, I choose to challenge sort method (>.<*), and I come out this code:
public void sorting(ArrayList< mypojo > theList) { Collections.sort(theList, new Comparator< mypojo >(){ @Override public int compare(MyPojo o1, MyPojo o2) { if( o1.getColumnA().compareToIgnoreCase(o2.getColumnA()) < 0 ) { return -1; } else if( o1.getColumnA().compareToIgnoreCase(o2.getColumnA()) == 0 ) { if( o1.getColumnB() == null || o2.getColumnB() == null ) { return 1; } else if( o1.getColumnB() != null && o2.getColumnB() != null && o1.getColumnB().compareToIgnoreCase(o2.getColumnB()) < 0 ) { return -1; } else if( o1.getColumnB() != null && o2.getColumnB() != null && o1.getColumnB().compareToIgnoreCase(o2.getColumnB()) > 0 ) { return 1; } else { return 0; } } else { return 1; } } }); }
And it works like charm. :o)
No comments:
Post a Comment