java list多字段排序_java中list通过多条件排序
實現的效果類似于這樣,首先通過一級類別id排序,其次是二級類別,最后是二級類別中的各項合計排序;
方法一
/**
* 單品容器排序
*
* @param productSellStatList
* @return
*/
private void getSortList(List productSellStatList) {
Collections.sort(productSellStatList, new Comparator() {
@Override
public int compare(ProductSellStat o1, ProductSellStat o2) {
if (o1.getParentProductTypeID() < o2.getParentProductTypeID()) {// 一級類目
return -1;
} else if (o1.getParentProductTypeID() == o2.getParentProductTypeID()) { // 一級類目
if (o1.getProductTypeID() < o2.getProductTypeID()) {
return 1;
} else if (o1.getProductTypeID() == o2.getProductTypeID()) { // 二級類目
if (o1.getRowTotal() > o2.getRowTotal()) { // 通過合計
return -1;
} else if (o1.getRowTotal() == o2.getRowTotal()) {// 通過合計
return 0;
} else {
return 1;
}
} else {
return 1;
}
} else {
return 1;
}
}
});
}
方法二
//productSellStatList為要排序的集合
List sortProductSellStatList = new ArrayList(productSellStatList.size()) ;
Map> tempMap = new HashMap>() ;
Comparator comparator = new TotalSaleComparator() ;
for (ProductSellStat p : productSellStatList) {
if (tempMap.isEmpty()) {
List tempList = new ArrayList() ;
tempList.add(p);
tempMap.put(p.getProductTypeID(), tempList) ;
} else {
if (tempMap.containsKey(p.getProductTypeID())) {
tempMap.get(p.getProductTypeID()).add(p);
} else {
// 為lis排序
for (List pList : tempMap.values()) {
Collections.sort(pList, comparator); // 排序
sortProductSellStatList.addAll(pList) ;
}
tempMap.clear();
}
}
if (tempMap.isEmpty()) {
List tempList = new ArrayList() ;
tempList.add(p);
tempMap.put(p.getProductTypeID(), tempList) ;
}
}
// 處理最后的內容
if (!tempMap.isEmpty()) {
// 為lis排序
for (List pList : tempMap.values()) {
Collections.sort(pList, comparator); // 排序
sortProductSellStatList.addAll(pList) ;
}
tempMap.clear();
}
productSellStatList.clear(); // 清空集合,方便垃圾回收
/**
* 銷量匯總排序
*/
public class TotalSaleComparator implements Comparator {
@Override
public int compare(ProductSellStat o1, ProductSellStat o2) {
if (o1.getRowTotal() > o2.getRowTotal()) {
return -1;
} else if (o1.getRowTotal() == o2.getRowTotal()) {
return 0;
} else {
return 1;
}
}
}
總結
以上是生活随笔為你收集整理的java list多字段排序_java中list通过多条件排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎么在windows安装python模块
- 下一篇: 迪米特法则 java_java设计模式-