我们有一个庞大的清单,每天都会更新。我们每天多次获取具有相同名称的每日文件,例如:
ABC_3102201912:13:00
BBC_3102201901:13:00
ABC_310201903:13:00
BBC_3102201904:13:00
ABC_010301912:13:00
BBC_0103201904:13:00
BBC_0103201906:13:00
and so on.....
我想将其放入Java集合中,并希望每天获取具有最新时间戳的文件,例如
For 31st
ABC_310201903:13:00
BBC_3102201904:13:00
For 1st
ABC_010301912:13:00
BBC_0103201906:13:00
我们如何使用Java集合轻松实现这一目标?
想到的一个想法是使用Collections.sort(),进行比较并找到max,但是Java集合中是否有任何直接方法可以实现这一点,而我们不需要手动比较?
您可以考虑使用TreeMap
,其中时间戳是键,而整个原始值就是该值。例如:
TreeMap<LocalDateTime, String> map = new TreeMap<>();
String input = "ABC_3102201912:13:00";
String ts = input.split("_")[1];
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyyHH:mm:ss");
LocalDateTime dt = LocalDateTime.parse(ts, formatter);
map.put(dt, input);
// print just the first entry from the descending map, which should be the most recent
for (Map.Entry<LocalDateTime, String> entry : map.descendingMap().entrySet()) {
LocalDateTime key = entry.getKey();
String value = entry.getValue();
System.out.println(key + " => " + value);
break;
}
上述解决方案从您的字符串时间戳输入中生成一个LocalDateTime
密钥,然后将原始值存储在TreeMap
中。通过迭代降序地图并仅打印第一个条目,我们可以访问对应于最新时间戳的条目。