I am trying to sort an arraylist based on groupings. Suppose I have a list of currency and cash USD 100, CAD 75, USD 10, EUR 80, USD 5
I want to sort the list based on maximum cash for a currency descending order, so required out should look like. USD 100, USD 10, USD 5, EUR 80, CAD 75.
I wrote below classes to achieve the same but no luck, can somebody help.
import java.math.BigDecimal;
import java.util.Comparator;
public class BO {
String ccy;
BigDecimal cash;
public String getCcy() {
return ccy;
}
public void setCcy(String ccy) {
this.ccy = ccy;
}
public BigDecimal getCash() {
return cash;
}
public void setCash(BigDecimal cash) {
this.cash = cash;
}
@Override
public String toString() {
return "BO [ccy=" + ccy + ", cash=" + cash + "]";
}
public static final Comparator<BO> CUSTOM_SORTER = new Comparator<BO>() {
@Override
public int compare(BO o1, BO o2) {
return o2.getCash().compareTo(o1.getCash());
}
};
}
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BODriver {
public static void main(String[] args) {
BO one = new BO();
one.setCcy("USD");
one.setCash(new BigDecimal(100));
BO two = new BO();
two.setCcy("CAD");
two.setCash(new BigDecimal(50));
BO three = new BO();
three.setCcy("USD");
three.setCash(new BigDecimal(10));
BO four = new BO();
four.setCcy("EUR");
four.setCash(new BigDecimal(70));
BO five = new BO();
five.setCcy("USD");
five.setCash(new BigDecimal(5));
List<BO> boList = new ArrayList<BO>();
boList.add(five);
boList.add(four);
boList.add(three);
boList.add(two);
boList.add(one);
System.out.println("Before sort");
System.out.println(boList);
Collections.sort(boList,BO.CUSTOM);
System.out.println("After sort");
System.out.println(boList);
}
}