Hi, lets say I have a sequence of objects (for sim...
# functional
s
Hi, lets say I have a sequence of objects (for simplicity I use strings):
Copy code
val s = sequenceOf("Lorem", "ipsum", "dolor", "sit", "amet")
What’s the best way to limit elements so total size is smaller than desired. For example:
Copy code
val s2 = s.someFunction(maxSize = 17) { it.length }
println(s2.toList()) // [Lorem, ipsum, dolor]
c
s.filter { it.length < 17 }
?
I guess you want total characters in the result list.
s
Yes 😉
c
You could use a fold maintaining like
Pair<Sequence<String>, Int>
or something?
s
I think there's a
limit(Int)
method? oh nvm you don't want to limit the number of elements. though maybe
flatMap{ it.chars.asSequence() }.limit(17)
would work? though it wouldn't keep the original strings
s
The idea is to make it work for more generic object (not String), so
asSequence
does not work.
e
Copy code
var total = 0
val limit = s.indexOfFirst {
    total += it.length
    total > 17
}
val s2 = s.take(if (limit >= 0) limit else s.size)
or
Copy code
val s2 = buildList {
    var total = 0
    for (t in s) (
        total += t.length
        if (total > 17) break
        add(t)
    }
}
s
Previous one creates state to a sequence so when run again it will not produce same result. But second example looks good and simple. Thanks.