What's the best way to go from a `Stream<T>`...
# announcements
j
What's the best way to go from a
Stream<T>
to a typed array of
Array<T>
? I need to convert a
Map<String,String>
to an
Array<Pair<String,String>>
. I've done this as follows:
Copy code
val array: Array<Pair<String, String>> = myMap.entries.stream().map {
        Pair(it.key, it.value)
    }.toList().toTypedArray()
Is that the most efficient way? It seems like converting to a
List
first and then to the (typed)
Array
has an extra step. But I'm not seeing any other way to go from the
Stream<Pair<String,String>>
coming out of the
map{}
function to a typed
Array<Pair<String,String>>
(since
Stream.toArray()
would give me an untyped Array of
Array<Any>
).
i
You don't need
stream
here at all: use
map.entries.toTypedArray()
Ô׼ 1
­čĹŹ 1
j
Cool, thanks. Didn't know about that function (obviously).
i
Oh, I see that you need an array of pairs, not an array of entries. Then
Copy code
val entryIterator = map.entries.iterator()
    val pairs = Array(map.size) { entryIterator.next().toPair() }
would be most efficient way. Not very fluent, though, and not recommended to use with concurrent maps.
j
Thanks, I was just about to follow up that I needed the
Pair
(as I'm calling a function from a library that takes a
vararg Pair<String, String>
)