SlideShare une entreprise Scribd logo
1  sur  153
Kotlin Collections
LazySoul
우명인
Collections
Mutable VS Immutable
Mutable
val mutableList: MutableList<Int> = mutableListOf(1,2,3,4,5)
mutableList.add(6)
for(i in 0 until mutableList.size){
println(mutableList.get(i)) //1, 2, 3, 4, 5, 6
}
Immutable
val immutableList: List<Int> = listOf(1,2,3,4,5)
immutableList.add(6) // Error
for(i in 0 until immutableList.size){
println(immutableList.get(i)) //1, 2, 3, 4, 5
}
Immutable
val immutableList: List<Int> = listOf(1,2,3,4,5)
immutableList.plus(6) // Ok
for(i in 0 until immutableList.size){
println(immutableList.get(i)) //1, 2, 3, 4, 5
}
Immutable
val immutableList: List<Int> = listOf(1,2,3,4,5)
val newList = immutableList.plus(6)
for(i in 0 until newList.size){
println(newList.get(i)) //1, 2, 3, 4, 5, 6
}
Immutable
• Kotlin은 함수형 패러다임을 반영합니다.
Immutable
• Kotlin은 함수형 패러다임을 반영합니다.
• 함수형 프로그래밍에서는 immutable(불변) 값을 사용해 사
이드 이펙트를 제거합니다.
Immutable
• Kotlin은 함수형 패러다임을 반영합니다.
• 함수형 프로그래밍에서는 immutable(불변) 값을 사용해 사
이드 이펙트를 제거합니다.
• 원본 리스트를 수정 하지 않고 수정된 새로운 리스트를 반
환합니다.
Immutable
• Kotlin은 함수형 패러다임을 반영합니다.
• 함수형 프로그래밍에서는 immutable(불변) 값을 사용해 사
이드 이펙트를 제거합니다.
• 원본 리스트를 수정 하지 않고 수정된 새로운 리스트를 반
환합니다.
• 함수적 자료구조에서 리스트를 수정하는 작업은, 기존 리스
트는 유지하고 조작되는 부분만 새로 생성하기때문에 오버
헤드가 없습니다.
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")
Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
• mutable 은 변경 가능한 collection을 말합니다.
Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
• mutable 은 변경 가능한 collection을 말합니다.
• immutable은 변경 불가능한 collection을 말합니다.
Collections
• Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection
이 존재합니다.
• mutable 은 변경 가능한 collection을 말합니다.
• immutable은 변경 불가능한 collection을 말합니다.
• mutable prefix가 없는 자료구조는 기본적으로 immutable 입니
다.
Aggregate operations
• any
• all
• count
• fold
• foldRight
• forEach
• forEachIndexed
• max
• maxBy
• minBy
• none
• reduce
• reduceRight
• sumBy
any
public fun <T> Iterable<T>.any(): Boolean {
for (element in this) return true
return false
}
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
any
public inline fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
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
all
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
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
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
}
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
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
}
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
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
}
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
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
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)" }))
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)
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) }))
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
실습
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
forEach
public inline fun <T> Iterable<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
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
forEachIndexed
public inline fun <T> Iterable<T>.forEachIndexed(action: (index: Int, T)
-> Unit): Unit {
var index = 0
for (item in this) action(index++, item)
}
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
*/
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
}
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
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
}
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)
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
}
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
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
}
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)
none
public fun <T> Iterable<T>.none(): Boolean {
for (element in this) return false
return true
}
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
none
public inline fun <T> Iterable<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
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
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
}
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
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
}
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
sum
public fun Iterable<Int>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
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
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
}
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
Filtering operations
• drop
• dropWhile
• dropLastWhile
• filter
• filterNot
• slice
• take
• takeLast
• takeWhile
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()
}
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]
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))
}
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]
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
}
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]
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()
}
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]
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
}
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]
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
}
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]
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
}
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]
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()
}
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]
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
}
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]
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
}
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]
Mapping operations
• map
• mapIndexed
• flatMap
• groupBy
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
}
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]
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
}
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]
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
}
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]
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
}
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]}
Elements operations
• contains
• elementAt
• elementAtOrElse
• elementAtOrNull
• first
• firstOrNull
• indexOf
• indexOfFirst
• indexOfLast
• last
• lastIndexOf
• lastOrNull
• single
• singleOrNull
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
elementAt
public inline fun <T> List<T>.elementAt(index: Int): T {
return get(index)
}
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
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)
}
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
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
}
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
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()
}
}
}
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
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.")
}
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
firstOrNull
public fun <T> List<T>.firstOrNull(): T? {
return if (isEmpty()) null else this[0]
}
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
firstOrNull
public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
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
indexOf
val list = listOf(1, 2, 3, 4, 5)
println(list.indexOf(3)) // 2
println(list.indexOf(7)) // -1
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
}
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
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
}
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
last
public fun <T> List<T>.last(): T {
if (isEmpty())
throw NoSuchElementException("List is empty.")
return this[lastIndex]
}
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
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.")
}
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
lastIndexOf
val list = listOf(1, 2, 3, 4, 5, 5, 5)
println(list.indexOf(5)) // 4
println(list.lastIndexOf(5)) // 6
println(list.lastIndexOf(8)) // -1
lastOrNull
public fun <T> List<T>.lastOrNull(): T? {
return if (isEmpty()) null else this[size - 1]
}
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
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
}
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
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.")
}
}
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>()
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
singleOrNull
public fun <T> List<T>.singleOrNull(): T? {
return if (size == 1) this[0] else null
}
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>()
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
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
}
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
Generation operations
• partition
• plus
• minus
• zip
• unzip
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)
}
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]
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
}
}
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]
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]
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 }
}
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]
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]
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
}
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)]
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)]
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
}
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])
Ordering operations
• reversed
• sorted
• sortBy
• sortDescending
• sortDescendingBy
reversed
public fun <T> Iterable<T>.reversed(): List<T> {
if (this is Collection && size <= 1) return toList()
val list = toMutableList()
list.reverse()
return list
}
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]
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() }
}
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]
sortBy
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T> {
return sortedWith(compareBy(selector))
}
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)]
sortByDescending
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) ->
R?): List<T> {
return sortedWith(compareByDescending(selector))
}
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)]
그래서?/* 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
그래서?
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))
그래서?
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))
val youngMidChamp = list.filter { it.position == Position.MID }
.minBy { it.age }
println("youngMidChamp : $youngMidChamp”)
// youngMidChamp : Person(name=Ari, age=19, position=MID)
그래서?
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))
val champsByPosition = list.groupBy { it.position }
.map {
it.value.joinToString(", ", prefix = "${it.key} : ") { it.name }
}
.joinToString("n")
println(champsByPosition)
// MID : Ari, Kassadin, Lux, Victor
// JUNGLE : Zac, Amumu
// TOP : Teemo
// BOTTOM : Ezreal

Contenu connexe

Tendances

Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meetMario Fusco
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monadJarek Ratajski
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsFranco Lombardo
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performanceintelliyole
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)intelliyole
 
Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianBrian Lonsdorf
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsBaruch Sadogursky
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with goEleanor McHugh
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }John De Goes
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиMaxim Kulsha
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101Ankur Gupta
 

Tendances (20)

Scala - where objects and functions meet
Scala - where objects and functions meetScala - where objects and functions meet
Scala - where objects and functions meet
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFrom java to kotlin beyond alt+shift+cmd+k - Droidcon italy
From java to kotlin beyond alt+shift+cmd+k - Droidcon italy
 
Kotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functionsKotlin from-scratch 2 - functions
Kotlin from-scratch 2 - functions
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
Pure kotlin
Pure kotlinPure kotlin
Pure kotlin
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)Feel of Kotlin (Berlin JUG 16 Apr 2015)
Feel of Kotlin (Berlin JUG 16 Apr 2015)
 
Benefits of Kotlin
Benefits of KotlinBenefits of Kotlin
Benefits of Kotlin
 
Functional Patterns for the non-mathematician
Functional Patterns for the non-mathematicianFunctional Patterns for the non-mathematician
Functional Patterns for the non-mathematician
 
The Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 SeasonsThe Groovy Puzzlers – The Complete 01 and 02 Seasons
The Groovy Puzzlers – The Complete 01 and 02 Seasons
 
Millionways
MillionwaysMillionways
Millionways
 
An introduction to functional programming with go
An introduction to functional programming with goAn introduction to functional programming with go
An introduction to functional programming with go
 
Atomically { Delete Your Actors }
Atomically { Delete Your Actors }Atomically { Delete Your Actors }
Atomically { Delete Your Actors }
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 

Similaire à Kotlin collections

Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowLeandro Ferreira
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)riue
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functionalHackraft
 
ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
 ReverseList.javaimport java.util.ArrayList;public class Rever.pdf ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
ReverseList.javaimport java.util.ArrayList;public class Rever.pdfaryan9007
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Waytdc-globalcode
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기진성 오
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory MappingQundeel
 
Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Alex Semin
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門Takashi Imahiro
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scaladjspiewak
 

Similaire à Kotlin collections (20)

Arrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com ArrowArrow 101 - Kotlin funcional com Arrow
Arrow 101 - Kotlin funcional com Arrow
 
Miracle of std lib
Miracle of std libMiracle of std lib
Miracle of std lib
 
関数潮流(Function Tendency)
関数潮流(Function Tendency)関数潮流(Function Tendency)
関数潮流(Function Tendency)
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
 
Swift Rocks #2: Going functional
Swift Rocks #2: Going functionalSwift Rocks #2: Going functional
Swift Rocks #2: Going functional
 
ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
 ReverseList.javaimport java.util.ArrayList;public class Rever.pdf ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
 
Python Lecture 11
Python Lecture 11Python Lecture 11
Python Lecture 11
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
Swift 함수 커링 사용하기
Swift 함수 커링 사용하기Swift 함수 커링 사용하기
Swift 함수 커링 사용하기
 
02 Arrays And Memory Mapping
02 Arrays And Memory Mapping02 Arrays And Memory Mapping
02 Arrays And Memory Mapping
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303Dip into Coroutines - KTUG Munich 202303
Dip into Coroutines - KTUG Munich 202303
 
Simpler java
Simpler javaSimpler java
Simpler java
 
Monadologie
MonadologieMonadologie
Monadologie
 
List out of lambda
List out of lambdaList out of lambda
List out of lambda
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門Scalaエンジニアのためのモナド入門
Scalaエンジニアのためのモナド入門
 
High Wizardry in the Land of Scala
High Wizardry in the Land of ScalaHigh Wizardry in the Land of Scala
High Wizardry in the Land of Scala
 

Plus de Myeongin Woo

DroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed classDroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed classMyeongin Woo
 
Lezhin kotlin jetbrain
Lezhin kotlin jetbrainLezhin kotlin jetbrain
Lezhin kotlin jetbrainMyeongin Woo
 
토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.Pptx토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.PptxMyeongin Woo
 

Plus de Myeongin Woo (8)

Goodbye null
Goodbye nullGoodbye null
Goodbye null
 
Fp basic-kotlin
Fp basic-kotlinFp basic-kotlin
Fp basic-kotlin
 
DroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed classDroidKnight 2018 State machine by Selaed class
DroidKnight 2018 State machine by Selaed class
 
Lezhin kotlin jetbrain
Lezhin kotlin jetbrainLezhin kotlin jetbrain
Lezhin kotlin jetbrain
 
Kotlin expression
Kotlin expressionKotlin expression
Kotlin expression
 
Kotlin with fp
Kotlin with fpKotlin with fp
Kotlin with fp
 
토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.Pptx토이 프로젝트를 하자.Pptx
토이 프로젝트를 하자.Pptx
 
Kotlin.md
Kotlin.mdKotlin.md
Kotlin.md
 

Dernier

VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 

Dernier (20)

VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 

Kotlin collections

  • 3. Mutable val mutableList: MutableList<Int> = mutableListOf(1,2,3,4,5) mutableList.add(6) for(i in 0 until mutableList.size){ println(mutableList.get(i)) //1, 2, 3, 4, 5, 6 }
  • 4. Immutable val immutableList: List<Int> = listOf(1,2,3,4,5) immutableList.add(6) // Error for(i in 0 until immutableList.size){ println(immutableList.get(i)) //1, 2, 3, 4, 5 }
  • 5. Immutable val immutableList: List<Int> = listOf(1,2,3,4,5) immutableList.plus(6) // Ok for(i in 0 until immutableList.size){ println(immutableList.get(i)) //1, 2, 3, 4, 5 }
  • 6. Immutable val immutableList: List<Int> = listOf(1,2,3,4,5) val newList = immutableList.plus(6) for(i in 0 until newList.size){ println(newList.get(i)) //1, 2, 3, 4, 5, 6 }
  • 7. Immutable • Kotlin은 함수형 패러다임을 반영합니다.
  • 8. Immutable • Kotlin은 함수형 패러다임을 반영합니다. • 함수형 프로그래밍에서는 immutable(불변) 값을 사용해 사 이드 이펙트를 제거합니다.
  • 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")
  • 12. Collections • Kotlin은 Java와 다르게 mutable, immutable 2가지의 collection 이 존재합니다.
  • 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 입니 다.
  • 16. Aggregate operations • any • all • count • fold • foldRight • forEach • forEachIndexed • max • maxBy • minBy • none • reduce • reduceRight • sumBy
  • 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
  • 55. sum public fun Iterable<Int>.sum(): Int { var sum: Int = 0 for (element in this) { sum += element } return sum }
  • 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
  • 59. Filtering operations • drop • dropWhile • dropLastWhile • filter • filterNot • slice • take • takeLast • takeWhile
  • 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]
  • 80. Mapping operations • map • mapIndexed • flatMap • groupBy
  • 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
  • 91. elementAt public inline fun <T> List<T>.elementAt(index: Int): T { return get(index) }
  • 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
  • 101. firstOrNull public fun <T> List<T>.firstOrNull(): T? { return if (isEmpty()) null else this[0] }
  • 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
  • 114. lastIndexOf val list = listOf(1, 2, 3, 4, 5, 5, 5) println(list.indexOf(5)) // 4 println(list.lastIndexOf(5)) // 6 println(list.lastIndexOf(8)) // -1
  • 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
  • 122. singleOrNull public fun <T> List<T>.singleOrNull(): T? { return if (size == 1) this[0] else null }
  • 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
  • 127. Generation operations • partition • plus • minus • zip • unzip
  • 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])
  • 141. Ordering operations • reversed • sorted • sortBy • sortDescending • sortDescendingBy
  • 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
  • 151. 그래서? 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))
  • 152. 그래서? 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)) val youngMidChamp = list.filter { it.position == Position.MID } .minBy { it.age } println("youngMidChamp : $youngMidChamp”) // youngMidChamp : Person(name=Ari, age=19, position=MID)
  • 153. 그래서? 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)) val champsByPosition = list.groupBy { it.position } .map { it.value.joinToString(", ", prefix = "${it.key} : ") { it.name } } .joinToString("n") println(champsByPosition) // MID : Ari, Kassadin, Lux, Victor // JUNGLE : Zac, Amumu // TOP : Teemo // BOTTOM : Ezreal