9. Immutable
• Kotlin은 함수형 패러다임을 반영합니다.
• 함수형 프로그래밍에서는 immutable(불변) 값을 사용해 사
이드 이펙트를 제거합니다.
• 원본 리스트를 수정 하지 않고 수정된 새로운 리스트를 반
환합니다.
10. Immutable
• Kotlin은 함수형 패러다임을 반영합니다.
• 함수형 프로그래밍에서는 immutable(불변) 값을 사용해 사
이드 이펙트를 제거합니다.
• 원본 리스트를 수정 하지 않고 수정된 새로운 리스트를 반
환합니다.
• 함수적 자료구조에서 리스트를 수정하는 작업은, 기존 리스
트는 유지하고 조작되는 부분만 새로 생성하기때문에 오버
헤드가 없습니다.
11. Collections
val list = listOf(1, 2, 3)
val mutableList = mutableListOf(1, 2, 3)
val set = setOf(1, 2, 3)
val mutableSet = mutableSetOf(1, 2, 3)
val map = mapOf(1 to "1", 2 to "2", 3 to "3")
val mutableMap = mutableMapOf(1 to "1", 2 to "2",
3 to "3")
13. Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
• mutable 은 변경 가능한 collection을 말합니다.
14. Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
• mutable 은 변경 가능한 collection을 말합니다.
• immutable은 변경 불가능한 collection을 말합니다.
15. Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
• mutable 은 변경 가능한 collection을 말합니다.
• immutable은 변경 불가능한 collection을 말합니다.
• mutable prefix가 없는 자료구조는 기본적으로 immutable 입니
다.
17. any
public fun <T> Iterable<T>.any(): Boolean {
for (element in this) return true
return false
}
18. any
public fun <T> Iterable<T>.any(): Boolean {
for (element in this) return true
return false
}
val list = listOf(1, 2, 3, 4, 5)
println(list.any()) //true
val emtpyList = listOf<Int>()
println(emtpyList.any()) //false
19. any
public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
20. any
public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
val list = listOf(1, 2, 3, 4, 5)
println(list.any { it > 3 }) // true
println(list.any { it > 0 }) // true
println(list.any { it > 5 }) // false
21. all
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
22. all
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
val list = listOf(1, 2, 3, 4, 5)
println(list.all { it > 3 }) // false
println(list.all { it > 0 }) // true
println(list.all { it > 5 }) // false
23. count
public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
24. count
public inline fun <T> Iterable<T>.count(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
val list = listOf(1, 2, 3, 4, 5)
println(list.count { it > 3 }) // 2
println(list.count { it > 0 }) // 5
println(list.count { it > 5 }) // 0
25. fold
public inline fun <T, R> Iterable<T>.fold(initial: R,
operation: (acc: R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
26. fold
public inline fun <T, R> Iterable<T>.fold(initial: R,
operation: (acc: R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
val list = listOf(1, 2, 3, 4, 5)
println(list.fold(0, { acc, next -> acc + next })) //15
27. foldRight
public inline fun <T, R> List<T>.foldRight(initial: R,
operation: (T, acc: R) -> R): R {
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
}
return accumulator
}
28. foldRight
public inline fun <T, R> List<T>.foldRight(initial: R,
operation: (T, acc: R) -> R): R {
var accumulator = initial
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
}
return accumulator
}
val list = listOf(1, 2, 3, 4, 5)
println(list.foldRight(0, { pre, acc -> pre + acc })) //15
29. fold vs foldRight
val list = listOf("a", "b", "c", "d", "e")
println(list.foldRight("", { pre, acc -> pre + acc })) //abcde
println(list.fold("", { acc, next -> acc + next })) //abcde
30. fold vs foldRight
val list = listOf("a", "b", "c", "d", "e")
println(list.foldRight("", { pre, acc -> pre + acc })) //abcde
println(list.fold("", { acc, next -> acc + next })) //abcde
println(list.foldRight(“”, { pre, acc -> "($pre + $acc)" }))
println(list.fold("", { acc, next -> "($acc + $next)" }))
31. fold vs foldRight
val list = listOf("a", "b", "c", "d", "e")
println(list.foldRight("", { pre, acc -> pre + acc })) //abcde
println(list.fold("", { acc, next -> acc + next })) //abcde
println(list.foldRight(“”, { pre, acc -> "($pre + $acc)" }))
//(a + (b + (c + (d + (e + )))))
println(list.fold("", { acc, next -> "($acc + $next)" }))
//((((( + a) + b) + c) + d) + e)
32. fold vs foldRight
val list = listOf("a", "b", "c", "d", "e")
println(list.foldRight("", { pre, acc -> pre + acc })) //abcde
println(list.fold("", { acc, next -> acc + next })) //abcde
println(list.foldRight(“”, { pre, acc -> "($pre + $acc)" }))
//(a + (b + (c + (d + (e + )))))
println(list.fold("", { acc, next -> "($acc + $next)" }))
//((((( + a) + b) + c) + d) + e)
val stringBuilderFR = StringBuilder()
println(list.foldRight(stringBuilderFR, { pre, acc -> stringBuilderFR.append(pre) }))
val stringBuilderFL = StringBuilder()
println(list.fold(stringBuilderFL, { acc, next -> stringBuilderFL.append(next) }))
33. fold vs foldRight
val list = listOf("a", "b", "c", "d", "e")
println(list.foldRight("", { pre, acc -> pre + acc })) //abcde
println(list.fold("", { acc, next -> acc + next })) //abcde
println(list.foldRight(“”, { pre, acc -> "($pre + $acc)" }))
//(a + (b + (c + (d + (e + )))))
println(list.fold("", { acc, next -> "($acc + $next)" }))
//((((( + a) + b) + c) + d) + e)
val stringBuilderFR = StringBuilder()
println(list.foldRight(stringBuilderFR, { pre, acc -> stringBuilderFR.append(pre) }))
// edcba
val stringBuilderFL = StringBuilder()
println(list.fold(stringBuilderFL, { acc, next -> stringBuilderFL.append(next) }))
//abcde
34. 실습
name, age 가 있는 person List를 만들고 (5개정도) fold를 이용해서 나이를 합산하는 코드
val list = listOf("a", "b", "c", "d", "e")
println(list.foldRight("", { pre, acc -> pre + acc })) //abcde
println(list.fold("", { acc, next -> acc + next })) //abcde
35. forEach
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
36. forEach
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
val list = listOf(1, 2, 3, 4, 5)
list.forEach { println(it) } // 1 2 3 4 5
37. forEachIndexed
public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T)
-> Unit): Unit {
var index = 0
for (item in this) action(index++, item)
}
38. forEachIndexed
public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T)
-> Unit): Unit {
var index = 0
for (item in this) action(index++, item)
}
val list = listOf(1, 2, 3, 4, 5)
list.forEachIndexed { index, value ->
println("idex = $index, value = $value")
}
/*
idex = 0, value = 1
idex = 1, value = 2
idex = 2, value = 3
idex = 3, value = 4
idex = 4, value = 5
*/
39. max
public fun <T : Comparable<T>> Iterable<T>.max(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
40. max
public fun <T : Comparable<T>> Iterable<T>.max(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
val list = listOf(1, 2, 3, 4, 5)
println(list.max()) // 5
41. maxBy
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R)
: T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = selector(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
42. maxBy
public inline fun <T, R : Comparable<R>> Iterable<T>.maxBy(selector: (T) -> R)
: T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = selector(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
val list = listOf(Person("a", 10),
Person("b", 30),
Person("c", 15))
println(list.maxBy { it.age }) //Person(name=b, age=30)
43. min
public fun <T : Comparable<T>> Iterable<T>.min(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
44. min
public fun <T : Comparable<T>> Iterable<T>.min(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
val list = listOf(1, 2, 3, 4, 5)
println(list.min()) // 1
45. minBy
public inline fun <T, R : Comparable<R>> Iterable<T>.minBy(selector: (T) -> R)
: T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = selector(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
46. minBy
public inline fun <T, R : Comparable<R>> Iterable<T>.minBy(selector: (T) -> R)
: T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = selector(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/* kotlin */
val list = listOf(Person("a", 10),
Person("b", 30),
Person("c", 15))
println(list.minBy { it.age }) //Person(name=a, age=10)
47. none
public fun <T> Iterable<T>.none(): Boolean {
for (element in this) return false
return true
}
48. none
public fun <T> Iterable<T>.none(): Boolean {
for (element in this) return false
return true
}
val list = listOf(1, 2, 3, 4, 5)
println(list.none()) //false
49. none
public inline fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
50. none
public inline fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
val list = listOf(1, 2, 3, 4, 5)
println(list.none { it > 0 }) //false
println(list.none { it < 0 }) //true
println(list.none { it > 3 }) //false
51. reduce
public inline fun <S, T: S> Iterable<T>.reduce(operation: (acc: S, T) -> S)
: S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
52. reduce
public inline fun <S, T: S> Iterable<T>.reduce(operation: (acc: S, T) -> S)
: S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty collection can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
val list = listOf(1, 2, 3, 4, 5)
println(list.reduce { acc, next -> acc + next }) //15
53. reduceRight
public inline fun <S, T: S> List<T>.reduceRight(operation: (T, acc: S) -> S)
: S {
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator
}
54. reduceRight
public inline fun <S, T: S> List<T>.reduceRight(operation: (T, acc: S) -> S)
: S {
val iterator = listIterator(size)
if (!iterator.hasPrevious())
throw UnsupportedOperationException("Empty list can't be reduced.")
var accumulator: S = iterator.previous()
while (iterator.hasPrevious()) {
accumulator = operation(iterator.previous(), accumulator)
}
return accumulator
}
val list = listOf(1, 2, 3, 4, 5)
println(list.reduceRight { before, acc -> before + acc }) //15
56. sum
public fun Iterable<Int>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
val list = listOf(1, 2, 3, 4, 5)
println(list.sum()) //15
57. sumBy
public inline fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int {
var sum: Int = 0
for (element in this) {
sum += selector(element)
}
return sum
}
58. sumBy
public inline fun <T> Iterable<T>.sumBy(selector: (T) -> Int): Int {
var sum: Int = 0
for (element in this) {
sum += selector(element)
}
return sum
}
/* kotlin */
val list = listOf(Person("a", 10),
Person("b", 30),
Person("c", 15))
println(list.sumBy { it.age }) // 55
60. drop
public fun <T> Iterable<T>.drop(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return toList()
val list: ArrayList<T>
if (this is Collection<*>) {
val resultSize = size - n
if (resultSize <= 0)
return emptyList()
if (resultSize == 1)
return listOf(last())
list = ArrayList<T>(resultSize)
if (this is List<T>) {
if (this is RandomAccess) {
for (index in n..size - 1)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list
}
}
else {
list = ArrayList<T>()
}
var count = 0
for (item in this) {
if (count++ >= n) list.add(item)
}
return list.optimizeReadOnlyList()
}
61. drop
public fun <T> Iterable<T>.drop(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return toList()
val list: ArrayList<T>
if (this is Collection<*>) {
val resultSize = size - n
if (resultSize <= 0)
return emptyList()
if (resultSize == 1)
return listOf(last())
list = ArrayList<T>(resultSize)
if (this is List<T>) {
if (this is RandomAccess) {
for (index in n..size - 1)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list
}
}
else {
list = ArrayList<T>()
}
var count = 0
for (item in this) {
if (count++ >= n) list.add(item)
}
return list.optimizeReadOnlyList()
}
val list = listOf(1, 2, 3, 4, 5)
println(list.drop(3)) // [4, 5]
62. dropLast
public fun <T> List<T>.dropLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return take((size - n).coerceAtLeast(0))
}
63. dropLast
public fun <T> List<T>.dropLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return take((size - n).coerceAtLeast(0))
}
val list = listOf(1, 2, 3, 4, 5)
println(list.dropLast(3)) // [1, 2]
64. dropWhile
public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T> {
var yielding = false
val list = ArrayList<T>()
for (item in this)
if (yielding)
list.add(item)
else if (!predicate(item)) {
list.add(item)
yielding = true
}
return list
}
65. dropWhile
public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T> {
var yielding = false
val list = ArrayList<T>()
for (item in this)
if (yielding)
list.add(item)
else if (!predicate(item)) {
list.add(item)
yielding = true
}
return list
}
val list = listOf(1, 2, 3, 4, 5)
println(list.dropWhile { it < 3 }) // [3, 4, 5]
66. dropLastWhile
public inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> {
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
return take(iterator.nextIndex() + 1)
}
}
}
return emptyList()
}
67. dropLastWhile
public inline fun <T> List<T>.dropLastWhile(predicate: (T) -> Boolean): List<T> {
if (!isEmpty()) {
val iterator = listIterator(size)
while (iterator.hasPrevious()) {
if (!predicate(iterator.previous())) {
return take(iterator.nextIndex() + 1)
}
}
}
return emptyList()
}
val list = listOf(1, 2, 3, 4, 5)
println(list.dropLastWhile { it > 3 }) // [1, 2, 3]
68. filter
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destination: C, predicate: (T) ->
Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
69. filter
public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destination: C, predicate: (T) ->
Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
val list = listOf(1, 2, 3, 4, 5)
println(list.filter { it > 3 }) // [4, 5]
70. filterNot
public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T> {
return filterNotTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(destination: C, predicate: (T) ->
Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
71. filterNot
public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T> {
return filterNotTo(ArrayList<T>(), predicate)
}
public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(destination: C, predicate: (T) ->
Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
val list = listOf(1, 2, 3, 4, 5)
println(list.filterNot { it > 3 }) // [1, 2, 3]
72. slice
public fun <T> List<T>.slice(indices: Iterable<Int>): List<T> {
val size = indices.collectionSizeOrDefault(10)
if (size == 0) return emptyList()
val list = ArrayList<T>(size)
for (index in indices) {
list.add(get(index))
}
return list
}
73. slice
public fun <T> List<T>.slice(indices: Iterable<Int>): List<T> {
val size = indices.collectionSizeOrDefault(10)
if (size == 0) return emptyList()
val list = ArrayList<T>(size)
for (index in indices) {
list.add(get(index))
}
return list
}
val list = listOf(1, 2, 3, 4, 5)
println(list.slice(listOf(2, 4))) // [3, 5]
74. take
public fun <T> Iterable<T>.take(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
if (this is Collection<T>) {
if (n >= size) return toList()
if (n == 1) return listOf(first())
}
var count = 0
val list = ArrayList<T>(n)
for (item in this) {
if (count++ == n)
break
list.add(item)
}
return list.optimizeReadOnlyList()
}
75. take
public fun <T> Iterable<T>.take(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
if (this is Collection<T>) {
if (n >= size) return toList()
if (n == 1) return listOf(first())
}
var count = 0
val list = ArrayList<T>(n)
for (item in this) {
if (count++ == n)
break
list.add(item)
}
return list.optimizeReadOnlyList()
}
val list = listOf(1, 2, 3, 4, 5)
println(list.take(3)) // [1, 2, 3]
76. takeLast
public fun <T> List<T>.takeLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
val size = size
if (n >= size) return toList()
if (n == 1) return listOf(last())
val list = ArrayList<T>(n)
if (this is RandomAccess) {
for (index in size - n .. size - 1)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list
}
77. takeLast
public fun <T> List<T>.takeLast(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) return emptyList()
val size = size
if (n >= size) return toList()
if (n == 1) return listOf(last())
val list = ArrayList<T>(n)
if (this is RandomAccess) {
for (index in size - n .. size - 1)
list.add(this[index])
} else {
for (item in listIterator(n))
list.add(item)
}
return list
}
val list = listOf(1, 2, 3, 4, 5)
println(list.takeLast(3)) // [3, 4, 5]
78. takeWhile
public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
if (!predicate(item))
break
list.add(item)
}
return list
}
79. takeWhile
public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T> {
val list = ArrayList<T>()
for (item in this) {
if (!predicate(item))
break
list.add(item)
}
return list
}
val list = listOf(1, 2, 3, 4, 5)
println(list.takeWhile { it < 3 }) // [1, 2]
81. map
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) ->
R): C {
for (item in this)
destination.add(transform(item))
return destination
}
82. map
public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapTo(destination: C, transform: (T) ->
R): C {
for (item in this)
destination.add(transform(item))
return destination
}
/* kotlin */
val list = listOf(Person("a", 10),
Person("b", 30),
Person("c", 15))
println(list.map { "${it.name} : ${it.age}" }) // [a : 10, b : 30, c : 15]
83. mapIndexed
public inline fun <T, R> Iterable<T>.mapIndexed(transform:
(index: Int, T) -> R): List<R> {
return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(destination: C, transform:
(index: Int, T) -> R): C {
var index = 0
for (item in this)
destination.add(transform(index++, item))
return destination
}
84. mapIndexed
public inline fun <T, R> Iterable<T>.mapIndexed(transform:
(index: Int, T) -> R): List<R> {
return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.mapIndexedTo(destination: C, transform:
(index: Int, T) -> R): C {
var index = 0
for (item in this)
destination.add(transform(index++, item))
return destination
}
/* kotlin */
val list = listOf(Person("a", 10),
Person("b", 30),
Person("c", 15))
println(list.mapIndexed { index, value -> "index $index = ${value.name}" })
// [index 0 = a, index 1 = b, index 2 = c]
85. flatMap
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -
> Iterable<R>): C {
for (element in this) {
val list = transform(element)
destination.addAll(list)
}
return destination
}
86. flatMap
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
return flatMapTo(ArrayList<R>(), transform)
}
public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -
> Iterable<R>): C {
for (element in this) {
val list = transform(element)
destination.addAll(list)
}
return destination
}
val list = listOf(1, 2, 3, 4, 5)
println(list.flatMap { listOf(it, it * 2, it * 3) })
// [1, 2, 3, 2, 4, 6, 3, 6, 9, 4, 8, 12, 5, 10, 15]
87. groupBy
public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}
public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M,
keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}
88. groupBy
public inline fun <T, K> Iterable<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}
public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByTo(destination: M,
keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}
val list = listOf(1, 2, 3, 4, 5)
println(list.groupBy { if (it % 2 == 0) "even" else "odd" })
// {odd=[1, 3, 5], even=[2, 4]}
89. Elements operations
• contains
• elementAt
• elementAtOrElse
• elementAtOrNull
• first
• firstOrNull
• indexOf
• indexOfFirst
• indexOfLast
• last
• lastIndexOf
• lastOrNull
• single
• singleOrNull
90. contains
val list = listOf(1, 2, 3, 4, 5)
println(list.contains(3)) //true
println(list.contains(6)) //false
println(list.containsAll(listOf(2, 5))) //true
println(list.containsAll(listOf(2, 6))) //false
92. elementAt
public inline fun <T> List<T>.elementAt(index: Int): T {
return get(index)
}
val list = listOf(1, 2, 3, 4, 5)
println(list.elementAt(2)) // 3
println(list.elementAt(7)) // Error
93. elementAtOrElse
public inline fun <T> List<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
94. elementAtOrElse
public inline fun <T> List<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
return if (index >= 0 && index <= lastIndex) get(index) else defaultValue(index)
}
val list = listOf(1, 2, 3, 4, 5)
println(list.elementAtOrElse(2, { it * 2 })) // 3
println(list.elementAtOrElse(10, { it * 2 })) // 20
95. elementAtOrNull
public inline fun <T> List<T>.elementAtOrNull(index: Int): T? {
return this.getOrNull(index)
}
public fun <T> List<T>.getOrNull(index: Int): T? {
return if (index >= 0 && index <= lastIndex) get(index) else null
}
96. elementAtOrNull
public inline fun <T> List<T>.elementAtOrNull(index: Int): T? {
return this.getOrNull(index)
}
public fun <T> List<T>.getOrNull(index: Int): T? {
return if (index >= 0 && index <= lastIndex) get(index) else null
}
val list = listOf(1, 2, 3, 4, 5)
println(list.elementAtOrNull(2)) // 3
println(list.elementAtOrNull(10)) // null
97. first
public fun <T> Iterable<T>.first(): T {
when (this) {
is List -> return this.first()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
return iterator.next()
}
}
}
98. first
public fun <T> Iterable<T>.first(): T {
when (this) {
is List -> return this.first()
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty.")
return iterator.next()
}
}
}
val list = listOf(1, 2, 3, 4, 5)
println(list.first()) // 1
println(listOf<Int>().first()) // Error
99. first
public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("Collection contains no element matching the predicate.")
}
100. first
public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("Collection contains no element matching the predicate.")
}
val list = listOf(1, 2, 3, 4, 5)
println(list.first { it > 3 }) // 4
println(list.first { it > 7 }) // Error
102. firstOrNull
public fun <T> List<T>.firstOrNull(): T? {
return if (isEmpty()) null else this[0]
}
val list = listOf(1, 2, 3, 4, 5)
println(list.firstOrNull()) // 1
println(listOf<Int>().firstOrNull()) // null
103. firstOrNull
public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
104. firstOrNull
public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
val list = listOf(1, 2, 3, 4, 5)
println(list.firstOrNull { it > 3 }) // 4
println(list.firstOrNull { it > 6 }) // null
105. indexOf
val list = listOf(1, 2, 3, 4, 5)
println(list.indexOf(3)) // 2
println(list.indexOf(7)) // -1
106. indexOfFirst
public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
107. indexOfFirst
public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
val list = listOf(1, 2, 3, 4, 5)
println(list.indexOfFirst { it > 3 }) // 3
println(list.indexOfFirst { it > 7 }) // -1
108. indexOfLast
public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (predicate(iterator.previous())) {
return iterator.nextIndex()
}
}
return -1
}
109. indexOfLast
public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
if (predicate(iterator.previous())) {
return iterator.nextIndex()
}
}
return -1
}
val list = listOf(1, 2, 3, 4, 5)
println(list.indexOfLast { it < 3 }) // 1
110. last
public fun <T> List<T>.last(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[lastIndex]
}
111. last
public fun <T> List<T>.last(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[lastIndex]
}
val list = listOf(1, 2, 3, 4, 5)
println(list.last()) // 5
println(listOf<Int>().last()) // Error
112. last
public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
throw NoSuchElementException("List contains no element matching the predicate.")
}
113. last
public inline fun <T> List<T>.last(predicate: (T) -> Boolean): T {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
throw NoSuchElementException("List contains no element matching the predicate.")
}
val list = listOf(1, 2, 3, 4, 5)
println(list.last { it > 3 }) // 5
println(list.last { it > 7 }) // Error
115. lastOrNull
public fun <T> List<T>.lastOrNull(): T? {
return if (isEmpty()) null else this[size - 1]
}
116. lastOrNull
public fun <T> List<T>.lastOrNull(): T? {
return if (isEmpty()) null else this[size - 1]
}
val list = listOf(1, 2, 3, 4, 5)
println(list.lastOrNull()) // 5
println(listOf<Int>().lastOrNull()) // null
117. lastOrNull
public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
return null
}
118. lastOrNull
public inline fun <T> List<T>.lastOrNull(predicate: (T) -> Boolean): T? {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
return null
}
val list = listOf(1, 2, 3, 4, 5)
println(list.lastOrNull { it > 3 }) // 5
println(list.lastOrNull { it > 7 }) // null
119. single
public fun <T> List<T>.single(): T {
return when (size) {
0 -> throw NoSuchElementException("List is empty.")
1 -> this[0]
else -> throw IllegalArgumentException("List has more than one element.")
}
}
120. single
public fun <T> List<T>.single(): T {
return when (size) {
0 -> throw NoSuchElementException("List is empty.")
1 -> this[0]
else -> throw IllegalArgumentException("List has more than one element.")
}
}
val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()
121. single
public fun <T> List<T>.single(): T {
return when (size) {
0 -> throw NoSuchElementException("List is empty.")
1 -> this[0]
else -> throw IllegalArgumentException("List has more than one element.")
}
}
val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()
println(list.single()) // Error
println(singleList.single()) // 1
println(emptyList.single()) // Error
123. singleOrNull
public fun <T> List<T>.singleOrNull(): T? {
return if (size == 1) this[0] else null
}
val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()
124. singleOrNull
public fun <T> List<T>.singleOrNull(): T? {
return if (size == 1) this[0] else null
}
val list = listOf(1, 2, 3, 4, 5)
val singleList = listOf(1)
val emptyList = listOf<Int>()
println(list.singleOrNull()) // null
println(singleList.singleOrNull()) // 1
println(emptyList.singleOrNull()) // null
125. singleOrNull
public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
126. singleOrNull
public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
println(list.singleOrNull { it > 3 }) // null
println(list.singleOrNull { it > 4 }) // 5
println(list.singleOrNull { it > 5 }) // null
128. partition
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
129. partition
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
val list = listOf(1, 2, 3, 4, 5)
println(list.partition { it % 2 == 0 }) // [2, 4], [1, 3, 5]
130. plus
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}
131. plus
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(1, 2, 3, 4, 5)
println(list.plus(list2)) // [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
132. plus
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
if (elements is Collection) {
val result = ArrayList<T>(this.size + elements.size)
result.addAll(this)
result.addAll(elements)
return result
} else {
val result = ArrayList<T>(this)
result.addAll(elements)
return result
}
}
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(1, 2, 3, 4, 5)
println(list.plus(list2)) // [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
println(list)// [1, 2, 3, 4, 5]
133. minus
public operator fun <T> Iterable<T>.minus(elements: Iterable<T>): List<T> {
val other = elements.convertToSetForSetOperationWith(this)
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
134. minus
public operator fun <T> Iterable<T>.minus(elements: Iterable<T>): List<T> {
val other = elements.convertToSetForSetOperationWith(this)
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(1, 2, 3)
println(list.minus(list2)) // [4, 5]
135. minus
public operator fun <T> Iterable<T>.minus(elements: Iterable<T>): List<T> {
val other = elements.convertToSetForSetOperationWith(this)
if (other.isEmpty())
return this.toList()
return this.filterNot { it in other }
}
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(1, 2, 3)
println(list.minus(list2)) // [4, 5]
println(list)// [1, 2, 3, 4, 5]
136. zip
public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform:
(a: T, b: R) -> V): List<V> {
val first = iterator()
val second = other.iterator()
val list = ArrayList<V>(minOf(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
while (first.hasNext() && second.hasNext()) {
list.add(transform(first.next(), second.next()))
}
return list
}
137. zip
public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform:
(a: T, b: R) -> V): List<V> {
val first = iterator()
val second = other.iterator()
val list = ArrayList<V>(minOf(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
while (first.hasNext() && second.hasNext()) {
list.add(transform(first.next(), second.next()))
}
return list
}
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(1, 2, 3, 4, 5)
println(list.zip(list2)) // [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
138. zip
public inline fun <T, R, V> Iterable<T>.zip(other: Iterable<R>, transform:
(a: T, b: R) -> V): List<V> {
val first = iterator()
val second = other.iterator()
val list = ArrayList<V>(minOf(collectionSizeOrDefault(10), other.collectionSizeOrDefault(10)))
while (first.hasNext() && second.hasNext()) {
list.add(transform(first.next(), second.next()))
}
return list
}
val list = listOf(1, 2, 3, 4, 5)
val list2 = listOf(1, 2, 3, 4, 5)
println(list.zip(list2)) // [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
val list3 = listOf(1, 2, 3)
println(list.zip(list3))// [(1, 1), (2, 2), (3, 3)]
139. unzip
public fun <T, R> Iterable<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val expectedSize = collectionSizeOrDefault(10)
val listT = ArrayList<T>(expectedSize)
val listR = ArrayList<R>(expectedSize)
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}
140. unzip
public fun <T, R> Iterable<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val expectedSize = collectionSizeOrDefault(10)
val listT = ArrayList<T>(expectedSize)
val listR = ArrayList<R>(expectedSize)
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}
val list = listOf(Pair(1, 5), Pair(2, 6), Pair(3, 7))
println(list.unzip()) // ([1, 2, 3], [5, 6, 7])
142. reversed
public fun <T> Iterable<T>.reversed(): List<T> {
if (this is Collection && size <= 1) return toList()
val list = toMutableList()
list.reverse()
return list
}
143. reversed
public fun <T> Iterable<T>.reversed(): List<T> {
if (this is Collection && size <= 1) return toList()
val list = toMutableList()
list.reverse()
return list
}
val list = listOf(1, 2, 3, 4, 5)
println(list.reversed()) // [5, 4, 3, 2, 1]
144. sorted
public fun <T : Comparable<T>> Iterable<T>.sorted(): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Comparable<T>>() as Array<T>).apply { sort() }.asList()
}
return toMutableList().apply { sort() }
}
145. sorted
public fun <T : Comparable<T>> Iterable<T>.sorted(): List<T> {
if (this is Collection) {
if (size <= 1) return this.toList()
@Suppress("UNCHECKED_CAST")
return (toTypedArray<Comparable<T>>() as Array<T>).apply { sort() }.asList()
}
return toMutableList().apply { sort() }
}
val list = listOf(1, 4, 2, 3, 5)
println(list.sorted()) // [1, 2, 3, 4, 5]
146. sortBy
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareBy(selector))
}
147. sortBy
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareBy(selector))
}
data class Person(val name: String, val age: Int)
val list = listOf(Person("myeongin", 32), Person("ari", 19),
Person("kasadin", 50), Person("amumu", 15))
println(list.sortedBy { it.age })
// [Person(name=amumu, age=15), Person(name=ari, age=19), Person(name=myeongin, age=32),
Person(name=kasadin, age=50)]
148. sortByDescending
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) ->
R?): List<T> {
return sortedWith(compareByDescending(selector))
}
149. sortByDescending
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) ->
R?): List<T> {
return sortedWith(compareByDescending(selector))
}
data class Person(val name: String, val age: Int)
val list = listOf(Person("myeongin", 32), Person("ari", 19),
Person("kasadin", 50), Person("amumu", 15))
println(list.sortedByDescending { it.age })
// [Person(name=kasadin, age=50), Person(name=myeongin, age=32), Person(name=ari, age=19),
Person(name=amumu, age=15)]
150. 그래서?/* Kotlin */
data class Person(val name: String, val age: Int, var position: Position)
enum class Position {
TOP, MID, BOTTOM, SUPPORT, JUNGLE
}
val list = listOf(
Person("Ari", 19, Position.MID),
Person("Kassadin", 50, Position.MID),
Person("Lux", 24, Position.MID),
Person("Zac", 40, Position.JUNGLE),
Person("Victor", 34, Position.MID),
Person("Teemo", 34, Position.TOP),
Person("Ezreal", 34, Position.BOTTOM),
Person("Amumu", 12, Position.JUNGLE))
1. 나이가 제일 어린 챔피언을 (name : name, age: age) 로 출력
2. 포지션 별로 분류 후 다음과 같이 출력
// MID : Ari, Kassadin, Lux, Victor
// JUNGLE : Zac, Amumu
// TOP : Teemo
// BOTTOM : Ezreal