list数组排序 Collections 按Date时间降序排列
@ResponseBody @RequestMapping(value = {"K12", "12"}) public String refurbishLights(KdDynamic kdDynamic, HttpServletRequest request, HttpServletResponse response, Model model) { List<KdDynamic> kdDynamics=kdDynamicService.findList(kdDynamic); Collections.sort(kdDynamics, new Comparator<KdDynamic>(){ /* * int compare(KdDynamic kd1, KdDynamic kd2) 返回一个基本类型的整型, * 返回负数表示:kd2 小于kd1, * 返回0 表示:kd1和kd2相等, * 返回正数表示:kd2大于kd1 */ public int compare(KdDynamic kd1, KdDynamic kd2) { //按照kd1的更新时间进行降序排列 if(kd2.getDtime().before(kd1.getDtime())){ return -1; } if(kd1.getDtime() == kd1.getDtime()){ return 0; } return 1; } }); String jsonStr = null; JSONArray array = new JSONArray(); /* Json格式的数组形式 */ JSONObject obj; /* json格式的单个对象形式 */ for (int i = 0; i < kdDynamics.size(); i++ ) { obj = new JSONObject(); obj.put( "dnum", kdDynamics.get(i).getDnum() ); obj.put( "dtime", df.format(kdDynamics.get(i).getDtime() )); /* json通过put方式以key-value形式填充 */ obj.put( "dcontext", kdDynamics.get(i).getDcontext() ); array.put(obj); /* 将JSONObject添加入JSONArray */ } model.addAttribute("index", "ddzt"); model.addAttribute( "kdDynamics", kdDynamics ); model.addAttribute( "kdDynamicsJSON", array.toString()); System.out.println("===================================="); System.out.println(array.toString()); System.out.println("===================================="); return array.toString(); }