This article explores different ways to join multiple lists in Kotlin.

1. Using flatMap() function

The flatMap() function returns a flattened list of elements yielded from invoking the specified transform function on each collection element. The idea is to create a list of lists, and flatten each list using the flatMap() function, and collect all the elements in a new list. This would translate to a simple code below:

Download Code

Output:

[Ruby on Rails, NodeJS, Go, PHP, Kotlin, Ruby, Perl]

2. Using addAll() function

Another solution is to create a new list and add elements of each list to it using the addAll() function, as shown below:

Download Code

Output:

[Ruby on Rails, NodeJS, Go, PHP, Kotlin, Ruby, Perl]

 
The code can be shortened using the forEach() function. Here’s the equivalent version of the above code:

Download Code

Output:

[Ruby on Rails, NodeJS, Go, PHP, Kotlin, Ruby, Perl]

3. Using plus operator

A simple and fairly efficient solution to concatenate multiple lists is using the plus operator, which creates a new list that is the combination of all the lists.

Download Code

Output:

[Ruby on Rails, NodeJS, Go, PHP, Kotlin, Ruby, Perl]

 
If we want to join only two equal-sized lists and pick up alternative elements from each list, the best option is to use the zip() function.

Download Code

Output:

[C, Java, C++, Kotlin]

That’s all about joining multiple lists in Kotlin.