The 30 second answer
For two lists I use Stream.concat of both streams and toList, which keeps the first list's elements before the second's. Adding distinct turns it into a union. Without streams, a new ArrayList of the first list plus addAll of the second is just as good. For many lists I flatMap a stream of lists, because the Javadoc warns that deeply nested concat calls can overflow the stack.
var a = List.of(1, 2, 3);
var b = List.of(3, 4);
var combined = Stream.concat(a.stream(), b.stream()).toList();
// [1, 2, 3, 3, 4]
var union = Stream.concat(a.stream(), b.stream()).distinct().toList();
// [1, 2, 3, 4]
var all = new ArrayList<>(a);
all.addAll(b);
// same elements, but a mutable ArrayList
var c = List.of(5);
var many = Stream.of(a, b, c).flatMap(List::stream).toList();
// [1, 2, 3, 3, 4, 5]Concat details from the Javadoc: the result is ordered if both inputs are ordered, and parallel if either input is parallel. Its implementation note warns that repeated concatenation builds deep call chains and can end in StackOverflowError. So do not call concat in a loop over many lists. Use Stream.of(...).flatMap(...), which the Javadoc itself suggests.
Complexity: O(n + m) time and space for every version. distinct adds a hash set of the seen elements.
Edge cases: Stream.toList() returns an unmodifiable list, so calling add on combined throws UnsupportedOperationException. Use the ArrayList version if the caller needs to change the result. Either list being empty just returns the other one's elements.
What interviewers listen for: that you choose the plain addAll when no stream operations follow, mention distinct for a union, and know the deep-concat warning.
Sources (2)
- Stream.concat (implementation note) and flatMapdocs.oracle.com
- ArrayList.addAlldocs.oracle.com