我正在使用 Spring Boot 应用程序,并尝试根据 Schedule POJO 类的 tag
获取最早的 timeStart
。
我有一个带有 getter 和 setter 方法的简单 bean -
时间表.java
public class Schedule {
private String id;
private String tag;
private String timeStart;
}
当我对此类列表进行 for 循环时,如下所示:-
List<Schedule> schedules = someAPI();
for (Schedule schedule : schedules) {
LOGGER.info("schedule : "+schedule );
}
然后我得到以下输出:-
schedule: [ID = 561, Tag = A1, timeStart = 2019-07-26 15:33:00]
schedule: [ID = 562, Tag = A1, timeStart = 2019-07-24 11:33:00]
schedule: [ID = 563, Tag = A1, timeStart = 2019-07-25 12:33:00]
schedule: [ID = 564, Tag = A2, timeStart = 2019-07-26 14:33:00]
schedule: [ID = 565, Tag = A2, timeStart = 2019-07-26 15:33:00]
现在我想通过标签名称
获取最小的timeStart
并将其存储在数据库中,因此我需要如下输出;-
A1 -> 2019-07-24 11:33:00
A2 -> 2019-07-26 14:33:00
我尝试了以下操作(将 timeStarts 按标签名称放入 HashMap 中)-
Map < String, ArrayList < String >> timeStartsByTag = new HashMap < String, ArrayList < String >> ();
ArrayList < String > timeStarts = new ArrayList < String > ();
for (Schedule schedule: schedules) {
if (timeStarts.isEmpty()) {
timeStarts.add(schedule.getTimeStart());
}
if (!timeStarts.isEmpty() && timeStartsByTag.containsKey(schedule.getTag())) {
timeStarts.add(schedule.getTimeStart());
}
timeStartsByTag.put(schedule.getTag(), timeStarts);
}
它不起作用。
最佳答案
在当前代码中,您不比较 timeStart
值。所以它无法工作。
除此之外,还可以使用需要合并函数的 Collectors.toMap()
重载来简化:
List<Schedule> schedules = someAPI();
Map<String, String> map =
schedules.stream()
.collect(toMap(Schedule::getTag, Schedule::getTimeStart,
(t1,t2)-> t1.compareTo(t2) < 0 ? t1 : t2))
);
这里 String.compareTo()
可以工作,因为字典顺序与您的当前要求相匹配,但这很脆弱。使用 LocalDateTime
或 Instant
来表示 2019-07-24 11:33:00
更有意义。
关于java - 根据bean属性值获取最早时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57674688/