David Callanan
David Callanan

Reputation: 5968

Does kotlin have a map function that returns an iterator?

If I map over a List in kotlin using .map, it returns a new list. Is there an equivalent that returns just an iterator for performance reasons?

This could be the same for Java, so I am also including that tag in this question.

Upvotes: 1

Views: 1561

Answers (1)

Joffrey
Joffrey

Reputation: 37710

It sort of depends on what you want to do with the iterator.

Kotlin has Sequences, which is the equivalent of Java 8's Streams, meaning they are lazy: they just provide elements when iterated upon (using any terminal operation like sum or count also counts as iterating).

So if what you're looking for is laziness, then go for sequences.

To create a sequence from a list, you can use asSequence():

val list = listOf(1, 2, 3)
val seq = list.asSequence().map { it * 2 }
// nothing happens as long as the sequence is not iterated upon
val result = coldSeq.toList() // now things are computed and added to a list

You can also directly create a sequence with sequenceOf.

If your goal is really to get a Java Iterator, you can get one from a sequence using .iterator().

Upvotes: 4

Related Questions