리스트, 세트 또는 맵에 주어진 조건에 맞는 요소가 하나라도 있으면 true를 반환합니다.
|
|
val shapeName = "Square" val hasSquareElement: Boolean = listOfShape.any { it.name == shapeName // 조건: shape의 이름이 "Square"인지 확인 } |
이 예제에서, shape의 이름이 “Square”와 같으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
출력: hasSquareElement = true
listOfShape에 “Square” shape이 있기 때문입니다.
리스트, 세트 또는 맵의 요소 중 주어진 조건에 맞는 요소가 하나도 없으면 true를 반환합니다.
|
|
val shapeName = "Square" val isNotSquare: Boolean = listOfShape.none { it.name == shapeName // 조건: shape의 이름이 "Square"인지 확인 } |
이 예제에서, 모든 shape의 이름이 “Square”와 같지 않으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
출력: isNotSquare = false
listOfShape에 “Square” shape이 하나 있기 때문입니다.
리스트, 세트 또는 맵의 모든 요소가 주어진 조건에 맞으면 true를 반환합니다.
|
|
val shapeName = "Square" val hasSameName: Boolean = listOfShape.all { it.name == shapeName // 조건: shape의 이름이 "Square"인지 확인 } |
이 예제에서, 모든 shape의 이름이 “Square”와 같으면 true를 반환하고, 그렇지 않으면 false를 반환합니다.
출력: hasSameName = false
모든 요소의 이름이 “Square”가 아니기 때문입니다.
컬렉션의 요소 수를 반환합니다.
|
|
val totalElement: Int = listOfShape.count() |
출력: totalElement = 4
listOfShape에 총 4개의 요소가 있기 때문입니다.
또한, 주어진 조건에 맞는 요소의 수를 반환합니다.
|
|
val shapeName = "Square" val totalSquareElement: Int = listOfShape.count { it.name == shapeName // 조건: shape의 이름이 "Square"인지 확인 } |
출력: totalSquareElement = 1
listOfShape에 “Square” shape이 하나 있기 때문입니다.
초기 값을 시작으로 왼쪽에서 오른쪽으로 현재 누적 값과 각 요소에 대해 주어진 연산을 적용하여 값을 누적합니다.
|
|
val numbers = listOf(1, 2, 3, 4, 5) val sum = numbers.fold(0) { acc, element -> acc + element } println("Sum of numbers: $sum") |
출력: Sum of numbers: 15
fold와 유사하지만, 추가적으로 인덱스 매개변수를 제공합니다.
|
|
val words = listOf("apple", "banana", "cherry") val result = words.foldIndexed("") { index, acc, element -> acc + "[$index: $element] " } println("Result: $result") |
출력: Result: [0: apple] [1: banana] [2: cherry]
지정된 인덱스를 기반으로 컬렉션에서 부분 리스트를 추출합니다.
|
|
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9) val result = numbers.slice(listOf(2, 4, 6)) println("Result: $result") |
출력: Result: [3, 5, 7]
핵심 요약 및 용어 정리
- indexOfFirst: 조건에 맞는 첫 번째 요소의 인덱스를 반환하며, 없으면 -1을 반환합니다.
- find: 조건에 맞는 첫 번째 요소를 반환하며, 없으면 null을 반환합니다.
- any: 조건에 맞는 요소가 하나라도 있으면 true를 반환합니다.
- none: 조건에 맞는 요소가 하나도 없으면 true를 반환합니다.
- all: 모든 요소가 조건에 맞으면 true를 반환합니다.
- count: 요소의 총 개수 또는 조건에 맞는 요소의 개수를 반환합니다.
- fold: 초기 값을 시작으로 요소에 대해 연산을 적용하여 누적 값을 계산합니다.
- foldIndexed: fold와 유사하지만, 인덱스를 추가로 제공합니다.
- slice: 지정된 인덱스를 기반으로 부분 리스트를 추출합니다.