【发布时间】:2017-12-01 06:15:12
【问题描述】:
我有一个列表,如何将其转换为可以将具有最小值的键作为键值对的 Map。我想将此代码转换为流。
Map<Long, Date> formToDate = new HashMap<>();
for(FormInstance formInstance : formInstances) {
if(formToDate.get(formInstance.getForm().getId()) == null) {
formToDate.put(formInstance.getForm().getId(), formInstance.getCreatedDate());
}
else{
Date prevDate = formToDate.get(formInstance.getForm().getId());
Date thisDate = formInstance.getCreatedDate();
formToDate.put(formInstance.getForm().getId(), prevDate.before(thisDate) ? prevDate : thisDate);
}
}
到这样的事情:
Map<Long, List<Date>> formToDate = formInstances.stream()
.collect(
Collectors.groupingBy(formInstance -> formInstance.getForm().getId(),
Collectors.mapping(FormInstance::getCreatedDate, Collectors.toList())));
但我不想返回列表,而是希望有最小的日期。
【问题讨论】:
-
请take the tour 了解该网站的运作方式以及此处的主题有哪些问题,并edit 相应地提出您的问题。另见:Why is "Can someone help me?" not an actual question?
-
也许你最好在这里写自己的
Collector。 -
或者也许使用
Collectors.minBy收集器...但是上面给出的代码不仅仅是返回最小的日期!
标签: java lambda java-8 stream java-stream