我很想知道如何改变:
for (UserIndex.CoachingArea coachingArea : userIndex.coachingAreas){
for (UserIndex.CoachingWeekRef coachingWeekRef : coachingArea.weeks){
if (coachingWeekRef.trackingDays != null){
for (UserIndex.TrackingDay trackingDay : coachingWeekRef.trackingDays)
if (!trackingDay.status.equals(TrackingStatusEnum.WAITING.toString())) {
trackingDataStore.saveFirstCheck(false);
}
}
}
}
正在进行中。 这就是我得到的:
Stream.of(userIndex.coachingAreas)
.forEach(coachingArea -> Stream.of(coachingArea.weeks)
.filter(coachingWeekRef -> coachingWeekRef.trackingDays != null)
.forEach(coachingWeekRef -> Stream.of(coachingWeekRef.trackingDays)
.filter(trackingDay -> !trackingDay.status.equals(TrackingStatusEnum.WAITING.toString()))
)
);
如何调用最后一种方法来保存数据?
答案 0 :(得分:1)
只需添加另一个forEach。但是这一次,使lambda成为一个陈述,而不是一个表达式(在它周围加上括号)。
final TrackingDataStore tds = trackingDataStore; // or whatever type it is
final String WAITING = TrackingStatusEnum.WAITING.toString();
Stream.of(userIndex.coachingAreas)
.forEach(coachingArea -> Stream.of(coachingArea.weeks)
.filter(coachingWeekRef -> coachingWeekRef.trackingDays != null)
.forEach(coachingWeekRef -> Stream.of(coachingWeekRef.trackingDays)
.filter(trackingDay -> !trackingDay.status.equals(WAITING))
.forEach(trackingDay -> { tds.saveFirstCheck(false); }) // <-- here
)
);
答案 1 :(得分:1)
您可以使用flatMap
:
Stream.of(userIndex.coachingAreas)
.flatMap(coachingArea -> Stream.of(coachingArea.weeks))
.filter(coachingWeekRef -> coachingWeekRef.trackingDays != null)
.flatMap(coachingWeekRef -> Stream.of(coachingWeekRef.trackingDays))
.filter(trackingDay -> !trackingDay.status.equals(TrackingStatusEnum.WAITING.toString()))
.forEach(trackingDay -> trackingDataStore.saveFirstCheck(false));
这假定您要为trackingDay
调用多个trackingDataStore.saveFirstCheck(false)
。
如果您只想拨打trackingDataStore.saveFirstCheck(false)
一次(如果所有过滤器都已通过),您可以使用findAny
:
Stream.of(userIndex.coachingAreas)
.flatMap(coachingArea -> Stream.of(coachingArea.weeks))
.filter(coachingWeekRef -> coachingWeekRef.trackingDays != null)
.flatMap(coachingWeekRef -> Stream.of(coachingWeekRef.trackingDays))
.filter(trackingDay -> !trackingDay.status.equals(TrackingStatusEnum.WAITING.toString()))
.findAny()
.ifPresent(trackingDay -> trackingDataStore.saveFirstCheck(false));