This article will teach you how to use comparator to order your collections, if you don't know this before , It will greatly helps you.
For example , we have an object called paymentVO with lots of fields inside, our requirement is to do ascending or descending order following a field called "paymentSequenceNo" to show it .
public static void ascendingSort(List<PaymentVO> list) { if (!list.isEmpty()) { Collections.sort(list,new Comparator() {
@Override public int compare(Object o1, Object o2) { PaymentVO nVo1 = (PaymentVO) o1; PaymentVO nVo2 = (PaymentVO) o2; return nVo1.getBankTradePaymentSeqNo().compareTo(nVo2.getBankTradePaymentSeqNo());
}}); } }
Similarly ,In descending order , Just change Collections.sort(..) to Collections.reverse(...) will do :
public static void desscendingSort(List<PaymentVO> list) { if (!list.isEmpty()) {
Collections.reverse(list,new Comparator() { @Override public int compare(Object o1, Object o2) { PaymentVO nVo1 = (PaymentVO) o1; PaymentVO nVo2 = (PaymentVO) o2; return nVo1.getBankTradePaymentSeqNo().compareTo(nVo2.getBankTradePaymentSeqNo());
}}); } }
In java 8 lambda expression will make it more readable , why not check that out on google
ReplyDelete