Rjbcc58
Rjbcc58

Reputation: 317

Is there a kotlin idiomatic way of checking that a sequence is at least N elements?

Looking for a Kotlin idiomatic way of establishing a sequence has a minimum number of elements. I've accomplished it with this so far:

fun <T> Sequence<T>.hasMinimum(threshold: Int): Boolean =
    take(threshold).toList().size == threshold

Is there a better way?

Upvotes: 6

Views: 825

Answers (2)

Jataro
Jataro

Reputation: 2588

fun <T> Sequence<T>.hasMinimum(threshold: Int) = take(threshold).count() == threshold

Upvotes: 5

Mojtaba Haddadi
Mojtaba Haddadi

Reputation: 1376

i think you can use count() because it is a terminal operator

Returns the number of elements in this sequence.

operation is terminal.

public fun <T> Sequence<T>.count(): Int {...}

for your case we can write it.

fun <T> Sequence<T>.hasMinimum(threshold: Int): Boolean =
            count() == threshold

Upvotes: 1

Related Questions