forked from kimriri/kotlin_study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RetrieveCollectionElement.kt
55 lines (46 loc) · 1.67 KB
/
RetrieveCollectionElement.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// ref : https://kotlinlang.org/docs/collection-parts.html#windowed
fun main() {
}
fun sliceCollectionSampleCode() {
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.slice(1..3))
println(numbers.slice(0..4 step 2))
println(numbers.slice(setOf(3, 5, 0)))
}
fun takeDropSampleCode() {
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.take(3))
println(numbers.takeLast(3))
println(numbers.drop(1))
println(numbers.dropLast(5))
}
fun takeDropSampleCodeWithPredicates() {
val numbers = listOf("one", "two", "three", "four", "five", "six")
println(numbers.takeWhile { !it.startsWith('f') })
println(numbers.takeLastWhile { it != "three" })
println(numbers.dropWhile { it.length == 3 })
println(numbers.dropLastWhile { it.contains('i') })
}
fun chunkSampleCode() {
val numbers = (0..13).toList()
println(numbers.chunked(3))
}
fun chunkWithTransformSampleCode() {
val numbers = (0..13).toList()
println(numbers.chunked(3) { it.sum() }) // `it` is a chunk of the original collection
}
fun windowedSampleCode() {
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.windowed(3))
}
fun windowedWithParamsSampleCode() {
val numbers = (1..10).toList()
println(numbers.windowed(3, step = 2, partialWindows = false))
println(numbers.windowed(3, step = 2, partialWindows = true))
println(numbers.windowed(3) { it.sum() })
}
fun zipWithNextSampleCode() {
val numbers = listOf("one", "two", "three", "four", "five")
println(numbers.zipWithNext())
println(numbers.zipWithNext() { s1, s2 -> s1.length > s2.length})
}