我有一个
class MedicationPeriod {
LocalDateTime startDate, endDate;
//assume getters and setters
}那我就有List<MedicationPeriod> medPrd = getMedPeriods();了
medPrd中的元素可能具有相同的startDate。
现在,我想过滤列表,以便对于具有相同startDate的元素,具有最大endDate的元素应该保留在列表中。也就是有最长的一天。
示例:如果列表元素是:
1) startDate =2018-1月1日,endDate =2018-2月25日// 25天
2) startDate =2018-1月1日,endDate =2018-2月20日/ 20天
3) startDate =2018-1月5日,endDate =2018-2月25日// startDate是不同的,我们不在乎
因此,最后的列表应该只有元素1)和元素3)。元素2将被删除,因为具有相同startDate的其他startDate具有更大的endDate。
这里是我(不愉快地工作)获得结果的尝试:
mps.stream().collect(Collectors.toMap(MedicationPeriod::getStartDate, e -> e, (a,b) -> a.endDate.isAfter(b.endDate) ? a : b)).values();My requirement:
List<MedicationPeriod>而不是Collection<MedicationPeriod>,因为我的解决方案给了Collection<>.values()的情况下实现这一点,因为我可以在流中进行进一步的转换,并在以后收集它们。假设我必须在过滤MedicationPeriods之后执行一些测试,然后将其收集到:
class DateRange {
LocalDate startDate, endDate;
}我怎样才能只用一个终端操作就能做到这一点?
发布于 2018-02-01 07:25:22
你的代码没有什么问题。它起作用了。只是做了一些重构
new ArrayList<>(medPrd.stream()
.collect(Collectors.toMap(MedicationPeriod::getStartDate, Function.identity(), (a, b) -> a.endDate.isAfter(b.endDate) ? a : b))
.entrySet()
.stream()
.map(entry -> new DateRange(entry.getValue().startDate, entry.getValue().getEndDate())).collect(Collectors.toList()));采纳@Holger的建议,看起来就像
new ArrayList<>(medPrd.stream()
.collect(Collectors.toMap(MedicationPeriod::getStartDate, Function.identity(), BinaryOperator.maxBy(Comparator.comparing(MedicationPeriod::getEndDate))))
.entrySet()
.stream()
.map(entry -> new DateRange(entry.getValue().startDate, entry.getValue().getEndDate())).collect(Collectors.toList()));https://stackoverflow.com/questions/48557048
复制相似问题