Android/Kotlin

[Kotlin] List, Set, Map, Collection Operations

Chef.Yeon 2022. 9. 16. 17:12

Collections

1. List

- ordered collection

- index로 원소에 접근 가능

listOf(1,2,2) --> [1,2,2]

2. Set

- unique elements

setOf(1,2,2) ---> [1,2]

3. <Map>

- key-value pairs

- 동일한 key에 대해 하나의 value만 가짐

mapOf("first" to 1, "second" to 2, "second" to 3) --> {first=1, seconde=3}

4. Type

    1) read-only

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

    2) mutable

      - 순서를 가지며, 변경이 가능

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

mutableIterator.next()
mutableIterator.remove() // [two, three, four]

 

Collection operations - Retrieve

1. position

- 데이터의 위치 정보 조회

    (1) index

val list = listOf(1,2,3,4,5)
println("${list.elementAt(0)}") // 0번째 원소 1 출력
println("${list.elementAtOrNull(5)}") // 해당 인덱스 데이터가 없으면 NUll 반환
println("${list.elementAtOrElse(5){-1}}") // 해당 인덱스 데이터가 없으면 기본값 지정

    (2) 확장함수

    - 특정 위치 요청

    - first() : 0번째 데이터 반환

    - fistOrNull() : 0번째 데이터가 없을 경우 Null 반환

    - last() : 마지막 데이터 반환

    - lastOrNull() : 마지막 데이터가 없을 경우 Null 반환

println("${list.first()}, ${list.firstOrNull()}")
println("${list.last()}, ${list.lastOrNull()}")

2. condition

- 함수의 argument로 조건 전달

// it : 리스트의 원소
// 리스트의 원소를 순차적으로 꺼내 3보다 큰 첫 번째 원소 출력
println("${list.firstOrNull {it > 3 }}") 
println("${list.find { it > 3 }}")

// 리스트의 원소를 마지막부터 순차적으로 꺼내 3보다 큰 첫 번째 원소 출력
println("${list.lastOrNull {it > 3 }}") 
println("${list.findLast { it > 3 }}")

 

Collection operations - Transformation

- 데이터의 반환 값을 변경하는 것과 관련된 연산

1. Map

val numbers = setOf(1,2,3)
println(numbers.map {it * 3}) // [3, 6, 9]
println(numbers.mapIndexed {idx, value -> value * idx}) // [0, 2, 6]

2. String representation

- separator : collection 원소의 구분자

- prefix : 문자열 처음에 붙을 문구

- postfix : 문자열 마지막에 붙을 문구

val numbers = listOf("one", "two", "three", "four")
println(numbers.joinToString(
    separator = " | ",
    prefix = "start: ",
    postfix = ": end"
))
// start: one | two | three | four: end

 

Collection operations - Filtering

- 데이터를 필터링하는 기준을 세우고 기준에 맞게 분류하는 연산

1. predicate

val numbers = listOf("one", "two", "three", "four")
// 문자열 길이가 3보다 큰 원소를 필터링해서 출력
val longerThan3 = numbers.filter {it.length > 3}
println(longerThan3) // [three, four]

 

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

println(numbers.any{it.endsWith("e")}) // true
println(numbers.none{it.endsWith("a")}) // true
println(numbers.all{it.endsWith("e")}) // false

- any : 조건을 만족하는 원소가 하나라도 있으면 true 반환

- none : 조건을 만족하는 원소가 하나라도 없을 때 true 반환

- all : 모든 원소가 조건을 만족해야 true 반환

 

2. partition

- 조건을 만족하는 그룹과 만족하지 못하는 그룹으로 분류하는 연산

val numbers = listOf("one", "two", "three", "four")
val (match, rest) = numbers.partition {it.length > 3}

println(match) // [three, four]
println(rest) // [one, two]

 

Collection operations - Grouping

private val products = arrayOf(
        Product("패션","겨울 패딩"),
        Product("패션","겨울 바지"),
        Product("전자기기","핸드폰"),
        Product("전자기기","블루투스 이어폰"),
        Product("전자기기","노트북"),
        Product("반려동물물품","건식사료"),
        Product("반려동물물품","습식사료"),
        Product("반려동물물품","치약"),
        Product("반려동물물품","간식"),
    )
private val categories: Map<String, List<Product>> = products.groupBy { product ->
    product.categoryLabel
}

categoryLabel을 key로 갖고 카테고리에 해당하는 상품 목록을 value로 갖는 Map 타입으로 변환

 

728x90