Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the elements from a list of lists with the Java Stream API in Kotlin

The following code (written in Kotlin) extracts the elements from a list of lists. It works, but looks rather ugly and difficult to read.

Is there a nicer way to write the same with the java stream api? (Examples can be given in Kotlin or Java)

val listOfLists: List<Any> = ...
val outList: MutableList<Any> = mutableListOf()

listOfLists.forEach {
    list ->
    if (list is ArrayList<*>) list.forEach {
        l ->
        outList.add(l)
    }
}

return outList;
like image 950
Fabian Avatar asked Jul 31 '17 07:07

Fabian


3 Answers

In Kotlin it's super easy without any excessive boilerplate:

val listOfLists: List<List<String>> = listOf()

val flattened: List<String> = listOfLists.flatten()

flatten() is the same as doing flatMap { it }


In Java, you need to utilize Stream API:

List<String> flattened = listOfLists.stream()
  .flatMap(List::stream)
  .collect(Collectors.toList());

You can also use Stream API in Kotlin:

val flattened: List<String> = listOfLists.stream()
  .flatMap { it.stream() }
  .collect(Collectors.toList())
like image 148
Grzegorz Piwowarek Avatar answered Nov 25 '22 06:11

Grzegorz Piwowarek


You could flatMap each list:

List<List<Object>> listOfLists = ...;
List<Object> flatList = 
    listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());
like image 37
Mureinik Avatar answered Nov 25 '22 05:11

Mureinik


Use flatMap

  List<Integer> extractedList = listOfLists.stream().flatMap(Collection::stream).collect(Collectors.toList());

flatMap() creates a stream out of each list in listOfLists. collect() collects the stream elements into a list.

like image 28
rohit Avatar answered Nov 25 '22 06:11

rohit