Where the return is List<List<String>> convert this result into List<String> only by combining the elements

Asked

Viewed 39 times

0

Considering the implementation below:

fun main(list: List<String>) {
    val x = 
        list
            .stream()
            .map { findMessages(it) }
            .collect(Collectors.toList())
}


fun findMessages(s: String) : List<String> {
    // return some list of strings   
}

I assign the implementation to x, but this x is typed as List<List<String>>. In case I take the collect(Collectors.toList()) would look like Stream<List<String>>.

But what I’d really like to have is a List<String> where each list returned by the method findMessages() merge with the previous list, but I’m not finding a simple way to do this.

An alternative solution would be this:

 fun main(list: List<String>) {
  val messagesToInput: ArrayList<String> = ArrayList()

    val x = 
        list
            .stream()
            .map { findMessages(it) }
            .map { it -> it.stream().map { messagesToInput.add(it) } }
}

But I believe there would be a more effective way than creating a list and assigning messages to it.

1 answer

1


You can use the flatMap to "flatten" the results on a single level, bringing Stream<List<String>> for only the content of streams List<String>:

    val x = 
        list
            .stream()
            .flatMap { findMessages(it).stream() }
            .collect(Collectors.toList())

Browser other questions tagged

You are not signed in. Login or sign up in order to post.