Contents

Java Stream join lists

Writen by: David Vlijmincx

Introduction

This post quickly explains how to join two lists using streams. I also show how to join two lists without using streams but with the list instances.

Using streams.concat()

The easiest way to join two lists with Streams is by using the Stream.concat(Stream a, Stream b) method. The method takes two Stream instances as parameters and puts the second Stream behind the first Stream. The result is a new list of strings with the content of both lists.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
List<String> listA = List.of("A","B","C");
List<String> listB = List.of("D","E","F");

List<String> concatLists = Stream
        .concat(listA.stream(), listB.stream())
        .collect(Collectors.toList());

// You can also use this shorter version if you have java 16 or higher
List<String> concatListsWithJava17 = Stream
        .concat(listA.stream(), listB.stream())
        .toList();

Using Stream.of()

We can also use Stream.of() to join two lists, but then we need an extra step to get a single list of strings. The result of Stream.of() is a list with lists. So we need to call .flatMap(Collection::stream) to map it to a single list of strings.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
List<String> listA = List.of("A","B","C");
List<String> listB = List.of("D","E","F");

List<String> flatMapLists = Stream
        .of(listA, listB)
        .flatMap(Collection::stream)
        .collect(Collectors.toList());

// You can also use this shorter version if you have java 16 or higher
List<String> flatMapListsWithJava17 = Stream
        .of(listA, listB)
        .flatMap(Collection::stream)
        .toList();

Using an ArrayList instance

The simplest way to add two lists is with the .addAll() method. This method adds the elements of one list to another one. The result is that the list instance calling the .addAll() method now contains the elements of both lists.

1
2
3
4
ArrayList<String> listC = new ArrayList<>(Arrays.asList("A","B","C"));
ArrayList<String> listE = new ArrayList<>(Arrays.asList("D","E","F"));

listC.addAll(listE);

Conclusion

In this post, we saw three ways to join lists in Java. We used the .concat() and Stream.of().flatMap(Collection::stream) methods to create a single lists using streams. We also used an instance of ArrayList to add elements of another list to itself.

 




Questions, comments, concerns?

Have a question or comment about the content? Feel free to reach out!