Learnitweb

Merge Two Lists Using Streams

Approach 1 — Using Stream.concat

List<T> merged = Stream.concat(a.stream(), b.stream())
    .collect(Collectors.toList());

Approach 2 — Using Stream.of + flatMap

List<T> merged2 = Stream.of(a, b)
    .flatMap(Collection::stream)
    .toList();

Explanation:

  • Stream.concat is ideal for merging two streams.
  • flatMap generalizes to merging multiple lists or collections in a single step.