Sunday, July 16, 2017

Using Comparator to sort


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());
  }});
 }
}

1 comment:

  1. In java 8 lambda expression will make it more readable , why not check that out on google

    ReplyDelete

Add Loading Spinner for web request.

when web page is busily loading. normally we need to add a spinner for the user to kill their waiting impatience. Here, 2 steps we need to d...