Collections.sort根据时间HH:mm排序List集合

构造了这么一个List<Map>

        List<Map<String, String>> itemList = new ArrayList<>();

        for (Map.Entry<String, String> e : entry) {
            String range = e.getKey();
            String curr = e.getValue();

            String[] curriculumIds = StringUtils.split(curr, ",");
            for (String c : curriculumIds) {
                Long curriculumId = Long.parseLong(c);
                Curriculum curriculum = curriculumService.getCurriculumById(curriculumId);
                String curriculumName = curriculum.getName();
                String channelName = curriculum.getChannel().getName();
                String teacherName = curriculum.getTeacher().getName();
                Map<String, String> item = new HashMap();

                item.put("timeRange", range);
                item.put("curriculumName", curriculumName);
                item.put("channelName", channelName);
                item.put("teacherName", teacherName);
                itemList.add(item);
            }
        }

排序的方法:

    private void sortListMap(List<Map<String, String>> data) {

        Collections.sort(data, new Comparator<Map<String, String>>() {
            @Override
            public int compare(Map<String, String> o1, Map<String, String> o2) {
                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                try {
                    Date d1 = format.parse(StringUtils.substringBefore(o1.get("timeRange"), "-"));
                    Date d2 = format.parse(StringUtils.substringBefore(o2.get("timeRange"), "-"));
                    return d1.compareTo(d2);
                } catch (ParseException e) {
                    return 0;
                }
            }
        });
    }

注:compartTo方法是前者减去后者

你可能感兴趣的:(Collections.sort根据时间HH:mm排序List集合)