java中对list进行排序(javaList排序问题)
java中对list进行排序(javaList排序问题)调用方法:public String SortTest(String sortName String recordDay String recordTime) { long start = System.currentTimeMillis(); System.out.println("从数据库获取时间 start:" start); List<Stock> stockList = this.stockWebManager.getAllStockList(recordDay recordTime); // 这里从数据库获取数据,什么都行 long end = System.currentTimeMillis(); System.out.println("从数据库获取时间 end:" end); System.o
一个通用的java排序,如果需要 整型的,或者 其他的,可以 用相应的替换掉 BigDecimal 就可以了。
使用场景,我的使用场景是股票分析,需要换手率排名,市值排名,主力净额,主力净占比,超大单净额,超大单净占比,等等,几十个可以排名的内容,如果按照普通的方式去写,好麻烦,于是就想了一个办法。通用排序就有啦。
先上结果:
程序使用时间
调用方法:
public String SortTest(String sortName String recordDay String recordTime) {
long start = System.currentTimeMillis();
System.out.println("从数据库获取时间 start:" start);
List<Stock> stockList = this.stockWebManager.getAllStockList(recordDay recordTime); // 这里从数据库获取数据,什么都行
long end = System.currentTimeMillis();
System.out.println("从数据库获取时间 end:" end);
System.out.println("从数据库获取时间 汇总 :" (end - start));
start = System.currentTimeMillis();
List<JSONObject> objList = new ArrayList<>();
for (Stock stock : stockList) {
objList.add((JSONObject) JSONObject.toJSON(stock)); // 获取的数据转换成 JSONObject 放在list里面。
}
end = System.currentTimeMillis();
System.out.println("转 JSONObject 汇总 :" (end - start));
start = System.currentTimeMillis();
List<Stock> sortStockList = new ArrayList<>();
List<JSONObject> sortObjList = this.sortBigDecimal(objList "stockCode" sortName "desc"); // 调用排序方法
for (JSONObject obj : sortObjList) {
sortStockList.add(JSONObject.toJavaObject(obj Stock.class)); // 将排序后的 JSONObject 再转换回来。
}
end = System.currentTimeMillis();
System.out.println("排序,并转回来, 汇总 :" (end - start));
return this.jsonResult.ok(sortStockList);
}
核心代码:
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
@Component("sortUtils")
public class SortUtils {
public List<JSONObject> sortBigDecimal(List<JSONObject> objList String uniqueKeyName String sortName String desc) {
List<JSONObject> resultList = new ArrayList<>();
List<BigDecimal> sortList = new ArrayList<>();
Map<BigDecimal Map<String JSONObject>> sortMap = new HashMap<>();
for (JSONObject obj : objList) {
if (sortMap.get(obj.getBigDecimal(sortName)) == null) {
sortMap.put(obj.getBigDecimal(sortName) new HashMap<>());
sortList.add(obj.getBigDecimal(sortName));
}
sortMap.get(obj.getBigDecimal(sortName)).put(obj.getString(uniqueKeyName) obj);
}
if (desc == null || desc.trim().length() == 0 || "desc".equals(desc.trim())) {
Collections.sort(sortList Collections.reverseOrder()); // 倒序
} else {
Collections.sort(sortList); // 正序
}
Map<String JSONObject> tmpMap;
for (BigDecimal i : sortList) {
tmpMap = sortMap.get(i);
for (JSONObject obj : tmpMap.values()) {
resultList.add(obj);
}
}
return resultList;
}
}