我需要帮助在java中按开始日期排序链接哈希映射列表。这是示例代码:
List<LinkedHashMap<String, String>> responseList = new ArrayList<LinkedHashMap<String, String>>();
response.put("EventID", 11);
response.put("EventName", "test");
response.put("Startdate", "11/20/2017");
responseList.add(response);
response.put("EventID", 22);
response.put("EventName", "test");
response.put("Startdate", "12/20/2017");
responseList.add(response);`
这只是带有2条记录的样本数据..我将实时拥有更多事件..事件发生的顺序是未知的...我想按开始日期对此responseList进行排序..任何人都可以帮忙。 ?
答案 0 :(得分:2)
使用对象而不是字符串集合。
使用三个成员变量定义一个类$code = "ces123456789101112131415";
Preg_match("/ces.{12}(\d+)/", $code, $match);
$pay = $match[1];
Echo $pay;
,类型为Event
或Integer
的id var,类型为String的名称var,以及类型为{{1}的start var }。解析输入字符串,并使用这些值来实例化Long
个对象。
以LocalDate
收集您的活动。使用Collections.sort
并传递Event
以使用List
进行排序。
不需要Comparator
。
Stack Overflow上已经多次介绍了这些步骤。搜索更多细节。
答案 1 :(得分:0)
此处不需要使用HashMap
。
避免重复数据的哈希映射,您可以将它们存储在类中并为其创建对象。创建 POJO 类,例如名为Events
,其中包含3个局部变量,例如: String eventId
,String name
和java.util.Date start
。创建他们的getter和setter。使用此课程进行进一步的操作。
设置活动的开始日期,并将所有活动添加到List<Event>
a。使用compareTo()
方法对List进行排序,您将获得所需的答案。使用Comparator
将创建自己的比较器。
答案 2 :(得分:-1)
您可以使用比较器对地图进行排序,该比较器是匿名内部类型,如下所示
List responseList = new LinkedList(response.entrySet());
// Defined Custom Comparator here
Collections.sort(responseList , new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});