How do I join two lists in Java?

There are several ways to join two lists in Java. Here are a few options:

  1. Using the addAll method of the List interface:
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.

  1. Using the Stream.concat method of the Stream class:
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.

  1. Using the addAll method of the List interface and the toArray method of the List interface:
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.