Java - How to merge two Lists into one

Here is how to join two Lists into one Lis.

List.addAll()

All items in the list passed as an argument to addAll() can be added to the list.

The following code adds both lists to one list.

List<String> list1 = new ArrayList<>();
list1.add("a1");
list1.add("a2");

List<String> list2 = new ArrayList<>();
list2.add("b1");
list2.add("b2");

List<String> joined = new ArrayList<>();
joined.addAll(list1);
joined.addAll(list2);

System.out.println(joined);

result

[a1, a2, b1, b2]

Guava

You can combine two lists into one using Guavas IterablesandLists`.

List<String> list1 = new ArrayList<>();
list1.add("a1");
list1.add("a2");

List<String> list2 = new ArrayList<>();
list2.add("b1");
list2.add("b2");

Iterable<String> joinedIterable = Iterables.unmodifiableIterable(
        Iterables.concat(list1, list2));
Collection<String> joined = Lists.newArrayList(joinedIterable);
System.out.println(joined);

result

[a1, a2, b1, b2]

Apache

Apaches ListUtils.union()` is an API that merges two lists into one and returns the combined list.

List<String> list1 = new ArrayList<>();
list1.add("a1");
list1.add("a2");

List<String> list2 = new ArrayList<>();
list2.add("b1");
list2.add("b2");

List<String> joined = ListUtils.union(list1, list2);
System.out.println(joined);

result

[a1, a2, b1, b2]

Stream

You can also create a list using Stream.

List<String> list1 = new ArrayList<>();
list1.add("a1");
list1.add("a2");

List<String> list2 = new ArrayList<>();
list2.add("b1");
list2.add("b2");

List<String> joined = Stream.concat(list1.stream(), list2.stream())
                            .collect(Collectors.toList());
System.out.println(joined);

result

[a1, a2, b1, b2]

You can select and add only the items you want using Stream`s filter().

The code below adds only strings containing 1 to the joined list.

List<String> list1 = new ArrayList<>();
list1.add("a1");
list1.add("a2");

List<String> list2 = new ArrayList<>();
list2.add("b1");
list2.add("b2");

List<String> joined = Stream.concat(list1.stream(), list2.stream())
                            .filter(s->s.contains("1"))
                            .collect(Collectors.toList());
System.out.println(joined);

result

[a1, b1]

Reference

codechachaCopyright ©2019 codechacha