1 回答
TA贡献1805条经验 获得超9个赞
对于流来说,这并不容易。首先,您需要按以下方式对您的回复进行排序startDate:
List<Response> sorted = responses.stream()
.sorted(Comparator.comparing(Response::getStartDate))
.collect(Collectors.toList());
不是创建将从变换方法Response来Request:
private static Request fromResponse(Response response) {
return new Request(response.getStartDate(), response.getEndDate(), response.getId());
}
最后是流操作:
List<Request> req = IntStream.range(0, sorted.size())
.boxed()
.flatMap(x -> {
if (x == responses.size() - 1) {
return Stream.of(fromResponse(responses.get(x)));
}
Response left = responses.get(x);
Response right = responses.get(x + 1);
if (!left.getEndDate().equals(right.getStartDate())) {
Response oneMore = new Response(
left.getEndDate(),
right.getStartDate(),
left.getId());
return Stream.of(fromResponse(left), fromResponse(oneMore));
} else {
return Stream.of(fromResponse(left));
}
})
.collect(Collectors.toList());
添加回答
举报