Appearance
How do I join two lists in Java?
There are several ways to join two lists in Java. Here are a few options:
- Using the
addAllmethod of theListinterface:
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");
List<String> list3 = new ArrayList<>(list1);
list3.addAll(list2);This creates a new mutable list list3 by copying list1 and appending list2. It's straightforward and efficient for basic concatenation without external dependencies.
- Using the
Stream.concatmethod of theStreamclass:
java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");
List<String> list3 = Stream.concat(list1.stream(), list2.stream())
.collect(Collectors.toList());This functional approach concatenates the streams of both lists and collects the result into a new list. It's concise and leverages Java's stream API for declarative data processing.
- Using the
Collections.addAllutility method:
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");
List<String> list3 = new ArrayList<>(list1);
Collections.addAll(list3, list2);This uses the Collections.addAll() utility method to efficiently append all elements from list2 to list3. It avoids stream overhead and is generally faster for simple list concatenation.
These are just a few options for joining two lists in Java. There are many other ways to do it as well.