使用 Collections.sort() 对集合进行排序,自定义 comparator 比较器,若涉及多条件排序,结合 thenComparing 使用。
实例:根据 areaid 和 storeno 排序,即 order by areaid desc, storeno desc
@RequestMapping(value = "/api/sortTest", method = RequestMethod.POST)
private List sortTest() {
List list = new ArrayList();
JSONObject oo1 = new JSONObject();
oo1.put("areaid", 101);
oo1.put("storeno", 222);
JSONObject oo2 = new JSONObject();
oo2.put("areaid", 102);
oo2.put("storeno", 210);
JSONObject oo3 = new JSONObject();
oo3.put("areaid", 101);
oo3.put("storeno", 220);
list.add(oo1);
list.add(oo2);
list.add(oo3);
Collections.sort(list, ((Comparator<JSONObject>) (o1, o2) -> {
Integer areaid1 = o1.getInteger("areaid");
Integer areaid2 = o2.getInteger("areaid");
return areaid1 - areaid2;
}).thenComparing((o1, o2) -> {
Integer storeno1 = o1.getInteger("storeno");
Integer storeno2 = o2.getInteger("storeno");
return storeno1 - storeno2;
}));
return list;
}