How to merge two lists
Short answer
Create a new list from the first one and add the second with addAll():
void main() {
var a = List.of(1, 2, 3);
var b = List.of(4, 5);
var merged = new ArrayList<>(a);
merged.addAll(b);
IO.println(merged);
}Output:
[1, 2, 3, 4, 5]With a stream
Stream.concat() joins two streams:
void main() {
var a = List.of("x", "y");
var b = List.of("z");
IO.println(Stream.concat(a.stream(), b.stream()).toList());
}Output:
[x, y, z]Many lists
For several lists use flatMap():
void main() {
var parts = List.of(List.of(1, 2), List.of(3), List.of(4, 5));
IO.println(parts.stream().flatMap(List::stream).toList());
}Output:
[1, 2, 3, 4, 5]Without duplicates
A LinkedHashSet removes duplicates and keeps the order:
void main() {
var a = List.of("java", "sql");
var b = List.of("sql", "git");
var union = new LinkedHashSet<>(a);
union.addAll(b);
IO.println(union);
}Output:
[java, sql, git]Common mistake
Calling addAll() on a list from List.of(). It is unmodifiable:
void main() {
var a = List.of(1, 2);
a.addAll(List.of(3));
}Output:
Exception in thread "main" java.lang.UnsupportedOperationExceptionFunctions used in this recipe
- List.addAll() — Adds all elements of another collection to a list.
- Stream.of() — Creates a stream from the listed values.
- LinkedHashSet — A set that remembers the insertion order of elements.