0

Is there a more simple and performant way of doing this, At the end I would need a list of scheduleContainers (List<ScheduleContainer>)

final List<ScheduleResponseContent> scheduleResponseContents = new ArrayList<>();
scheduleResponseWrappers.parallelStream().forEach(srw -> scheduleResponseContents.addAll(srw.getScheduleResponseContents()));
final List<List<ScheduleContainer>> schedulesOfWeek = new ArrayList<>();
scheduleResponseContents.parallelStream().forEach(src -> schedulesOfWeek.addAll(src.getSchedules()));
final List<ScheduleContainer> schedules = new ArrayList<>();
schedulesOfWeek.parallelStream().forEach(s -> schedules.addAll(s));
peteb
  • 18,552
  • 9
  • 50
  • 62
quma
  • 5,233
  • 26
  • 80
  • 146
  • you need a list which combines all of your list results? – george Aug 22 '16 at 19:59
  • 2
    You absolutely need to read this: http://stackoverflow.com/questions/20375176/should-i-always-use-a-parallel-stream-when-possible. Not only your code shouldn't use parallel streams because it's unnecessary, but worse: it's not thread-safe. – JB Nizet Aug 22 '16 at 20:08
  • 3
    Augh! Your code is totally not thread-safe; you're cramming stuff in parallel into a poor helpless `ArrayList`. You need to immediately get out of your habit of using `parallelStream` by default. – Brian Goetz Aug 22 '16 at 20:09
  • 1
    It seems you're looking for flatMap(). – JB Nizet Aug 22 '16 at 20:10
  • 2
    And use `collect()` instead of `forEach()`. – Brian Goetz Aug 22 '16 at 20:11

1 Answers1

1

Because of missing classes, I can just assume this is correct:

final List<ScheduleContainer> schedules = scheduleResponseWrappers.stream()
    .flatMap(srw -> srw.getScheduleResponseContents().stream())
    .flatMap(src -> src.getSchedules().stream())
    .collect(Collectors.toList());
bartac
  • 106
  • 5