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:
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 will create a new list list3 that contains the elements of list1 followed by the elements of list2.
- Using the
Stream.concatmethod of theStreamclass:
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 will create a new list list3 that contains the elements of list1 followed by the elements of list2.
- Using the
addAllmethod of theListinterface and thetoArraymethod of theListinterface:
List<String> list1 = Arrays.asList("a", "b", "c");
List<String> list2 = Arrays.asList("d", "e", "f");
List<String> list3 = new ArrayList<>(list1);
list3.addAll(Arrays.asList(list2.toArray(new String[0])));This will create a new list list3 that contains the elements of list1 followed by the elements of list2.
These are just a few options for joining two lists in Java. There are many other ways to do it as well.