본문 바로가기
Do it 코틀린 프로그래밍

코틀린 컬렉션(2) - List 활용하기

by 차누감 2020. 8. 24.

List는 순서에 따라 정렬된 요소를 가지는 컬렉션으로, 가장 많이 사용하는 컬렉션 중에 하나입니다.

 

불변형 List 생성하기

listOf() 함수

    var numbers: List<Int> = listOf(1,2,3,4,5)
    var names: List<String> = listOf("one","two","three")
    var mixedTypes = listOf("Hello", 1, 2.45, 's')  //  <Any>타입

    for (number in numbers) print(number)   //  12345
    println()
    for (index in names.indices) print("names[$index] = ${names[index]}")   //  names[0] = onenames[1] = twonames[2] = three

    for (index in names.indices){   //  짝수 요소만
        if(index%2==0)print("names[$index] = ${names[index]}")
    }

 

emptyList() 함수

비어있는 List를 생성하려면 emptyList<>()를 사용할 수 있습니다.

    val emptyList: List<String> = emptyList<String>()

 

listOfNotNull() 함수

    val nonNullsList: List<Int> = listOfNotNull(2, 45, 2, null, 5, null)
    println(nonNullsList)   //  [2, 45, 2, 5]

 

List의 주요 멤버 메서드

멤버 메서드 설명
get(index: Int) 특정 인덱스를 인자로 받아 해당 요소를 반환한다.
indexOf(element: E) 인자로 받은 요소가 첫 번째로 나타나는 인덱스를 반환하며,
없으면 -1을 반환한다.
lastIndexOf(element: E) 인자로 받은 요소가 마지막으로 나타나는 인덱스를 반환하고,
없으면 -1을 반환한다.
listIterator() 목록에 있는 iterator를 반환한다.
subList(fromIndex: Int, toIndex: Int) 특정 인덱스의 from과 to 범위에 있는 요소 목록을 반환한다.

 

List의 기본 멤버 메소드 사용해 보기
    var names: List<String> = listOf("one", "two","three")
        
    println(names.size) //  List 크기     3
    println(names.get(0))   //  해당 인덱스의 요소 가져오기     one
    println(names.indexOf("three")) //  해당 요소의 인덱스 가져오기     2
    println(names.contains("two"))  // 포함 여부 확인 후 포함되어 있으면 true 반환      true

 

가변형 List 생성하기

가변형 arrayListOf() 함수

    //  가변형 List를 생성하고 자바의 ArrayList로 반환
    val stringList: ArrayList<String> = arrayListOf<String>("Hello", "Kotlin", "Wow")
    stringList.add("Java")  //  추가
    stringList.remove("Hello")  // 삭제
    println(stringList) //  [Kotlin, Wow, Java]

 

가변형 mutableListOf() 함수

    //  가변형 List의 생성 및 추가, 삭제, 변경
    val mutableList: MutableList<String> = mutableListOf<String>("kildong","Dooly","Chelsu")
    mutableList.add("Ben")  //  추가
    mutableList.removeAt(1) //  인덱스 1번 삭제
    mutableList[0]="Sean"   //  인덱스 0번을 변경, set(index: Int, element: E)와 같은 역할
    println(mutableList)    //  [Sean, Chelsu, Ben]

    //  자료형의 혼합
    val mutableListMixed = mutableListOf("Android", "Apple",5,6,'X')
    println(mutableListMixed)   //  [Android, Apple, 5, 6, X]

 

불변형 List를 가변형으로 변환하기

    val names: List<String> = listOf("one", "two","three")  //  불변형 List 초기화
    val mutableNames = names.toMutableList()    //  새로운 가변형 List가 만들어짐
    mutableNames.add("four")    //  가변형 List에 하나의 요소 추가
    println(mutableNames)   //  [one, two, three, four]

'Do it 코틀린 프로그래밍' 카테고리의 다른 글

코틀린 시퀀스  (1) 2020.09.05
코틀린 컬렉션(3) - Set과 Map 활용하기  (1) 2020.08.25
코틀린 컬렉션(1) - 기본 구조  (1) 2020.08.23
코틀린 문자열  (0) 2020.08.22
코틀린 배열  (0) 2020.08.21

댓글