7

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;
1
  • Why do you need Java Streams for that? The Kotlin API is more than enough Commented Jul 31, 2017 at 11:44

3 Answers 3

18

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())
Sign up to request clarification or add additional context in comments.

Comments

8

You could flatMap each list:

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.