Retrieving items from a list of lists using Java Stream API in Kotlin

The following code (written in Kotlin) retrieves items from a list of lists. It works, but it looks pretty ugly and difficult to read.

Is there a better way to write the same with the java api stream? (Examples can be quoted 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;

      

+3


source to share


3 answers


In Kotlin, this is very easy without any over-the-top boilerplate:

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

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

      

flatten()

coincides with flatMap { it }




In Java, you need to use the Stream API:

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

      

You can also use the Stream API in Kotlin:

val flattened: List<String> = listOfLists.stream()
  .flatMap { it.stream() }
  .collect(Collectors.toList())

      

+6


source


You can flatMap

each list:



List<List<Object>> listOfLists = ...;
List<Object> flatList = 
    listOfLists.stream().flatMap(List::stream).collect(Collectors.toList());

      

+8


source


Use flatMap

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

      

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

0


source







All Articles