1. mutableList vs imutableList
fun main() {
val currencyList = listOf("1", "2", "3")
val mutableListOf = mutableListOf<String>()
mutableListOf.add("1")
mutableListOf.add("2")
mutableListOf.add("3")
val mutableListOf = mutableListOf<String>()
.apply {
add("1")
add("2")
add("3")
}
}
- immutableList는 불변 , mutableList는 변경이 가능하다
- immutableList는 add()라는 메소드가 없다. (불변이기 때문에 초기 생성시 값을 넣어주고 그뒤로 변경불가)
- .apply{}를 사용하면 좀더 가독성 좋게 만들어 줄 수 있음
2. mutableSet vs immutableSet
fun main() {
val immutableSet = setOf<Int>(1, 2, 3, 4)
val mutableSet = mutableSetOf<Int>().apply {
add(1)
add(2)
add(3)
add(4)
}
}
- immutableSet은 불변 mutableSet은 변경이 가능하다
- immutableSet은 add를 사용할 수 없음
- .apply{}를 사용하여 가독성 좋게 코드작성 가능
3. mutableMap vs ImmutableMap
fun main() {
val mapOf = mapOf("ont" to 1, "two" to 2)
val mutableMapOf = mutableMapOf<String, Int>()
mutableMapOf["one"] = 1
mutableMapOf["two"] = 2
mutableMapOf["three"] = 3
mutableMapOf.put("four", 4)
}
- mapOf는 immutableMap , mutableMapOf는 mutableMap임
- immutableMap은 ("key" to "value") 형식으로 값을 넣어줌
- mutableMap은 [key] = value같은 방식으로 값을 넣어 줄 수 있음
- put을 통해서도 넣을수 있지만, 추천하는 방식은 아님
- 4. buildList
fun main() {
val buildList : List<Int> = buildList<Int> {
add(1)
add(2)
add(3)
}
}
- buildList는 내부에서 mutableList으로 생성하지만, 리턴타입은 immutableList형식으로 반환된다.
5. 그 외 리스트
fun main() {
val linkedList = LinkedList<Int>().apply {
addFirst(3)
add(2)
addLast(1)
}
val arrayList = ArrayList<Int>().apply{
add(1)
add(2)
add(3)
}
}
- LinkedList나, ArrayList를 사용하고 싶다면 기존과 동일한 방식으로 생성해서 사용하면 된다.
6. iterator
fun main() {
val list = listOf(1, 2, 3)
val iterator = list.iterator()
while (iterator.hasNext()) {
println(iterator.next())
}
println("===================")
for (number in list) {
println(number)
}
println("===================")
list.forEach {
println(it)
}
}
- list는 iterator를 구현하고 있기 때문에 iterator를 사용할 수 있음
- while 반복문과 같이 hasnext를 통해 다음값을 확인하고 next를 통해 값을 불러 올 수 있음
- for 반복문도 사용가능(java와 동일)
- forEach도 가능(java와 동일)
7. map, filter
fun main() {
val list = listOf(1, 2, 3)
val addNumber = list.map {
it + 1
}
println(addNumber)
println("===================")
val filterNumbers = addNumber.filter { it > 2 }
println(filterNumbers)
// java
val filterNumbers_java = addNumber.stream().filter { it > 2 }
.collect(Collectors.toList())
println(filterNumbers_java)
val filterNumbers_with_Sequence = addNumber
.asSequence()
.filter { it > 2 }
.filter { it > 2 }
.filter { it > 2 }
.filter { it > 2 }
.toList()
println(filterNumbers_with_Sequence)
}
- map을 통해 해당 리스트를 다른 형태의 값으로 리턴할 수 있음(java와 동일함)
- filter를 통해 해당 리스트에서 바로 필요한 값만 필터링 할수 있음(java와 동일함)
- kotlin은 java와 다르게 Stream()과 마지막 터미널오퍼레티러.collect(Collectors.toList())를 사용하지 않음
- filter 갯수만큼 새로운 객체를 생성하는데, 많은 데이터를 처리할때는 out of memory에러가 발생할 수 있음
그것이 싫다면 asSequence()를 사용하자(마지막에 터미널오퍼레이터를 사용해줘야함 (toList()) )