我有一个如下列表:-
List<ScheduleActionDispatchDTO> pendingScheduleActions
=restClientApi.getPendingSchedules();
上面的列表来自DB,其值如下-
schedule_request_id = 576, user_id = 24,
start_time_utc = '2022-12-16 21:00:00', end_time_utc = '2022-12-17 01:00:00',
request_json = '{"testId": "5", "grade": "A"}'
schedule_request_id = 576, user_id = 24,
start_time_utc = '2022-12-16 21:00:00', end_time_utc = '2022-12-17 01:00:00',
request_json = '{"subjectId": "10", "name": "dictation"}'
schedule_request_id = 577, user_id = 24, start_time_utc = '2022-12-17 21:00:00',
end_time_utc = '2022-12-18 01:00:00', request_json = '{"testId": "5", "grade": "A"}'
现在我想要的结果是这样的,如果schedule_request_id
,user_id
,start_time_utc
和end_time_utc
的任何行值是相同的,然后合并这些行的request_json
的值在一起。
应该变成-
schedule_request_id = 576, user_id = 24,
start_time_utc = '2022-12-16 21:00:00', end_time_utc = '2022-12-17 01:00:00',
combinedResult = '[{"testId": "5", "grade": "A"}, {"subjectId": "10", "name": "dictation"}]'
和
schedule_request_id = 577, user_id = 24, start_time_utc = '2022-12-17 21:00:00',
end_time_utc = '2022-12-18 01:00:00', combinedResult = '{"testId": "5", "grade": "A"}'
I tried this -
Map<Long, List<ScheduleActionDispatchDTO>> requestMap = pendingScheduleActions.stream()
.collect(Collectors.groupingBy(
ScheduleActionDispatchDTO::getScheduleRequestId, Collectors.toList()));
for (Map.Entry<Long, List<ScheduleActionDispatchDTO>> entry : requestMap.entrySet()) {
List<ScheduleActionDispatchDTO> sameRequestActions = entry.getValue();
Map<ScheduleActionDispatchPair, ScheduleActionDispatchDTO> schedulePairAction =
sameRequestActions.stream().
collect(Collectors.toMap(
s -> new ScheduleActionDispatchPair(s.getScheduleRequestId(), s.getUserUd(), s.getStartTimeUtc(), s.getEndTimeUtc()),
s -> s));
// iterate and combine but not sure how
}
可以这样做。我假设您有如下形式的1记录:
public record PendingScheduleAction(
long scheduleRequestId,
int userId,
LocalDateTime startTimeUtc,
LocalDateTime endTimeUtc,
String requestJson
) { }
我们可以首先创建一个Merger
,它被用作分组键。我们添加了一个ofPendingScheduleAction
方法,这是一个方便的方法来简化分组。我们还添加了一个merge
方法,它可以合并两个PendingScheduleAction
对象。
record Merger(long scheduleRequestId, int userId, LocalDateTime startTimeUtc, LocalDateTime endTimeUtc) {
public static Merger ofPendingScheduleAction(PendingScheduleAction action) {
return new Merger(action.scheduleRequestId(), action.userId(), action.startTimeUtc(), action.endTimeUtc());
}
private static PendingScheduleAction merge(PendingScheduleAction a, PendingScheduleAction b) {
String json = a.requestJson() + ' ' + b.requestJson();
return new PendingScheduleAction(a.scheduleRequestId(), a.userId(), a.startTimeUtc(), a.endTimeUtc(), json);
}
}
现在你可以利用groupingBy
,reducing
和collectingAndThen
来达到预期的结果:
list.stream()
.collect(groupingBy(Merger::ofPendingScheduleAction, collectingAndThen(reducing(Merger::merge), optional -> {
var entry = optional.orElseThrow();
String[] jsonLines = entry.requestJson().split("