Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

flatten
arraylist
kotlin
communitycreator

How to use the flatten method of the ArrayList in Kotlin

Programming Bytes

Overview

Let’s say we have a list containing the list type as an element. We can use the flatten method to create a new list containing all the sub-list elements in this scenario.

Hierarchy for the "flatten" method

Syntax

fun <T> Iterable<Iterable<T>>.flatten(): List<T>

Arguments

This method doesn’t take any arguments.

Return value

This method returns a new list containing all the elements of the sublist of the list on which this method is invoked.

Code example

The code written below demonstrates how we use the flatten method:

fun main() {

  var list = arrayListOf(listOf(1,2), listOf(3,4))
  println("The ArrayList is $list")
  
  val newList = list.flatten()
  println("The flattened list is $newList")
}
Using the "flatten" method

Code explanation

  • Line 3: We create a new ArrayList with the name list, using the arrayListOf method. We pass two lists, listOf(1,2) and listOf(3,4), as arguments to the arrayListOf method. Hence, we get an ArrayList with two list elements as the elements of the list.

  • Line 6: We use the flatten method to get a new list containing all the elements of the sub-list that are present in the list. In our case, the list elements are [1,2] and [3,4]. These are flattened to 1,2,3,4 and returned as a new list. Hence, we get [1,2,3,4] as a result.

RELATED TAGS

flatten
arraylist
kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring