본문 바로가기
코틀린/[Filtering] 필터 작업

[Kotlin][Collection] removeFirst / removeLast / removeAt

by jinwo_o 2024. 9. 6.

이 변경 가능한 목록에서 첫 번째 요소를 제거하고 제거된 요소를 반환하거나, 이 목록이 비어 있으면 NoSuchElementException을 발생시킵니다.

public fun <T> MutableList<T>.removeFirst(): T = if (isEmpty()) throw NoSuchElementException("List is empty.") else removeAt(0)


val list = mutableListOf(1, 2, 3, 4)
print(list.removeFirst()) // 1
print(list) // [2, 3, 4]

 

이 변경 가능한 목록에서 마지막 요소를 제거하고 제거된 요소를 반환하거나, 이 목록이 비어 있으면 NoSuchElementException을 발생시킵니다.

public fun <T> MutableList<T>.removeLast(): T = if (isEmpty()) throw NoSuchElementException("List is empty.") else removeAt(lastIndex)


val list = mutableListOf(1, 2, 3, 4)
print(list.removeLast()) // 4
print(list) // [1, 2, 3]

 

목록에서 지정된 인덱스에 있는 요소를 제거합니다. 제거된 요소를 반환합니다.

val list = mutableListOf(1, 2, 3, 4)
print(list.removeAt(2)) // 3
print(list) // [1, 2, 4]

 

removeFirst - Kotlin Programming Language

 

kotlinlang.org

 

removeLast - Kotlin Programming Language

 

kotlinlang.org

 

removeAt - Kotlin Programming Language

 

kotlinlang.org

'코틀린 > [Filtering] 필터 작업' 카테고리의 다른 글

[Kotlin][Map] containsKey, containsValue  (0) 2024.09.10
[Kotlin][Collection] distinct  (0) 2024.09.05
[Kotlin][Number] coerceAtMost  (0) 2024.09.02