SlandShow
SlandShow

Reputation: 513

Kotlin sequences: filter + find first + map

In Java streams API i can make something like this:

someStream.stream()
          .filter(someCondition)
          .findFirst()
          .map(someMappingStatement)
          .orElse(null)

And i wan't to do the same code with sequences:

someSequence.asSequence()
            .filter{ someCondition }
            .map{ someMappingStatement }
            .firstOrNull()

I have some worries about findFirst(). Because in sequences here i filter, then map all, but not first element. How can i rewrite it better in sequences?

Upvotes: 7

Views: 10426

Answers (1)

Tenfour04
Tenfour04

Reputation: 93581

In this case it doesn't matter which order these two operations occur. You could swap firstOrNull and map by replacing map with let, but there wouldn't be any significant difference in computation time, specifically because you're working with a Sequence rather than a List. With a Sequence, the fact that you use firstOrNull as your terminal operation means that the map function will only be run on that first element.

Upvotes: 6

Related Questions