[kotlin] Collection & Sequence

kotlin standard libary에는 Container type으로 Collection과 Sequence(Sequence) 두가지 타입을 가지고 있다.

Collection

Collection은 대부분 언어에서 라이브러리로 제공된다. C++에는 STL이 있고 python은 자체적으로 제공한다. 제공하는 방식이 다를뿐 사용법에 있어서는 비슷하다고 할 수 있다. 그럼 kotlin에서 제공되는 collection 함수 set, list, map을 세개를 제공한다.공식 문서 참조

특징을 간단히 정리하면 read only와 mutable 두가지 종류로 나뉜다.

val numbers = mutableListOf("one", "two", "three", "four")

// read only 
val wordRep = listOf("key","http","one","two","github","kotlin")

위의 코드 처럼 세가지 타입의 collection들이 모두 읽기 전용과 가변한 용기(container)을 제공한다.

자세한 내용은 위의 공식 문서 혹은 이 블로그를 참고하시기 바란다

자주 사용하는 내장 함수들

Collection 합치기 - union()

val numbers = setOf("one","two)"
println(numbers union setOf("four", "five")

Collection 공통element 찾기 - intersect

//A, B 는 String, 두 String의 공통 문자 존재 여부 체크
val setA = A.toSet()
val setB = B.toSet()
return setA.intersect(setB).isNotEmpty()

Collection 한쪽에만 있는 element 찾기 - subtract

//A, B 는 String, 두 String이 같은지 비교 
val setA = A.toSet()
val setB = B.toSet()
return setA.subtract(setB).isNotEmpty()

DistInct

중복원소 제거

val setA = A.toSet().distinct()

Sequence

위의 collection 같은 경우 filter를 사용하는 경우에 대하여 매번 모든 item에 대하여 연산하는 반면에

Sequence는 실제 요청이 들어 왔을때 연산을 함으로써 실제 연산이 느리게 진행된다(executed lazily)

val words = "The quick brown fox jumps over the lazy dog".split(" ") 
//convert the List to a Sequence
val wordsSequence = words.asSequence()
val lengthsSequence = wordsSequence.filter { println("filter: $it"); it.length > 3 }
    .map { println("length: ${it.length}"); it.length }
    .take(4) 
println("Lengths of first 4 words longer than 3 chars") 
// terminal operation: obtaining the result as a List 
println(lengthsSequence.toList())

위의 코드에서 볼수 있듯이 sequence는 모든 구문이 모두 실행되여야 다음 이터레이션이 실행되는 형태이고 조건에 맞게 item을 모무 찾으면 종료 된다. 그 원인으로 filter 조건이 앞쪽에 오는 것이 좋다

 

Ref:

https://iosroid.tistory.com/79

https://kotlinlang.org/docs/sequences.html

https://iosroid.tistory.com/88

Collection을 잘 사용한 예