项目中遇到在内存中重新排序问题,将list集合按照对象中某些属性进行排序
//items 先按照 显示顺序Orders排序,Orders相同按照时间CreateTime排序
List<Object> collect = items.stream().sorted(new Comparator<Object>() {
@Override
public int compare(Objecto1, Objecto2) {
if(o1.getOrders()>o2.getOrders()){
return 1;
}else if (o1.getOrders().equals(o2.getOrders())){
if(o1.getCreateTime().before(o2.getCreateTime()) ){
return 1;
}else if(o1.getCreateTime()==o2.getCreateTime()){
return 0;
}else{
return -1;
}
}else{
return -1;
}
}
}).collect(Collectors.toList());
JSONArray根据某一属性排序
JSONObject json = JSONObject.parseObject(s);
//重新排序
JSONArray array = new JSONArray();
JSONArray list = (JSONArray)json.get("item");
for (Object o : list) {
JSONObject jsonObject = JSONObject.parseObject(o.toString());
JSONArray im_log_infos =(JSONArray) jsonObject.get("im_log_infos");
Integer logId = (Integer)jsonObject.get("im_sub_session_id");
//降序排列
// im_log_infos.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("created_at")).reversed());
//升序
im_log_infos.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("created_at")));
JSONObject jsonO = new JSONObject();
jsonO.put("im_sub_session_id",logId);
jsonO.put("im_log_infos",im_log_infos);
array.add(jsonO);
}
json.put("item", array);
model.addAttribute("IMMsg",json.toString());