Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 740
SlandShow Avatar asked Aug 06 '26 04:08

SlandShow


1 Answers

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.

like image 53
Tenfour04 Avatar answered Aug 07 '26 19:08

Tenfour04



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!