跳到主內容

Kotlin集合運算子整理總表Iterable/Collection/List/Set/Map

出處 : https://blog.csdn.net/vitaviva/article/details/107587134

建立集合 

不可變更集合 immutable

import java.util.*
import java.text.SimpleDateFormat
/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
fun main() {
    val list = listOf(1,2,3, null)
    // 不為 null List
    val notNullList = listOfNotNull(null,1,2,3,null)
    val map = mapOf("foo" to "FOO", "bar" to "BAR", "bar" to "BB")
    val set = setOf(4,5,6,6)
    println(list) 			// 	[1, 2, 3, null]
    println(notNullList) 	//	[1, 2, 3]
    println(map)			// 	{foo=FOO, bar=BB}
    println(set)			// 	[4, 5, 6]
}
  

可變更集合 mutable

import java.util.*
import java.text.SimpleDateFormat
/**
 * You can edit, run, and share this code.
 * play.kotlinlang.org
 */
fun main() {
  val list = mutableListOf(1,2,3,3)
  val map = mutableMapOf("foo" to "FOO", "bar" to "BAR", "bar" to "BB")
  val set = mutableSetOf(1,2,3,3)
  println(list) // [1, 2, 3, 3]
  println(map)	// {foo=FOO, bar=BB}
  println(set)	// [1, 2, 3]
}
  

Stream 與 kotlin 比較

image-1704942398795.png