Requirement Overview
A recent client request required implementing multi-column sorting for a list query.
Analysis Approach
Given the manageable data volume, direct retrieval followed by in-memory sorting using Collections.sort was deemed appropriate.
Implementation Strategy
The solution involved creating a custom comparator to handle complex sorting logic. The apprroach utilized a dedicated sorting class that could process multiple criteria based on specified parameters.
public class MultiColumnSorter implements Comparator<StockComparisonVO> {
private String orderDirection;
public MultiColumnSorter() {}
public MultiColumnSorter(String direction) {
this.orderDirection = direction;
}
@Override
public int compare(StockComparisonVO item1, StockComparisonVO item2) {
int diff1 = item1.getStockDifference() != null ?
item1.getStockDifference().intValue() : 0;
int diff2 = item2.getStockDifference() != null ?
item2.getStockDifference().intValue() : 0;
diff1 = Math.abs(diff1);
diff2 = Math.abs(diff2);
if ("desc".equals(orderDirection)) {
if (diff1 == 0 && diff2 == 0) {
if (item1.getCompanyStock() != null && item2.getCompanyStock() != null) {
return item2.getCompanyStock().compareTo(item1.getCompanyStock());
} else if (item1.getCustomsTheoreticalStock() != null &&
item2.getCustomsTheoreticalStock() != null) {
return item2.getCustomsTheoreticalStock().compareTo(
item1.getCustomsTheoreticalStock());
}
return 1;
} else {
return diff2 - diff1;
}
} else if ("asc".equals(orderDirection)) {
if (diff1 == 0 && diff2 == 0) {
if (item1.getCompanyStock() != null && item2.getCompanyStock() != null) {
return item1.getCompanyStock().compareTo(item2.getCompanyStock());
} else if (item1.getCustomsTheoreticalStock() != null &&
item2.getCustomsTheoreticalStock() != null) {
return item1.getCustomsTheoreticalStock().compareTo(
item2.getCustomsTheoreticalStock());
}
return 1;
} else {
return diff1 - diff2;
}
} else {
return 1;
}
}
}
The implementation accepts a parameter to detemrine sorting direction. Usage involves calling:
Collections.sort(dataList, new MultiColumnSorter(String.valueOf(requestParams.getOrder())));
After deployment and testing, the solution successfully handled both ascending and descending orders according to specifications.