6.3 Kotlin集合类型之Map、MutableMap

Kotlin集合类型之Map、MutableMap

Map是一个接口和通用的元素集合。 Map以键和值对的形式保存数据。 映射的键是唯一的,每个键只保留一个值。 键和值可以是不同类型。 也被分为可变的和不可变的,即Map与MutableMap.

Map

它是不可变的,它的大小固定,方法支持只读访问。要使用Map接口,需要使用mapOf()或mapOf <k,v>()函数声明。

声明和创建Map集合

声明和创建Map有很多方式,下面一一介绍:
mapOf()声明一个空的map: 返回一个只读的空的map
源码:

/**
 * Returns an empty read-only map.
 *
 * The returned map is serializable (JVM).
 * @sample samples.collections.Maps.Instantiation.emptyReadOnlyMap
 */
@kotlin.internal.InlineOnly
public inline fun <K, V> mapOf(): Map<K, V> = emptyMap()

声明:

val first = mapOf<String, String>()

mapOf()声明非空Map: 返回不可变的Map集合。接收多个key-value对,这些key-value对将作为Map的元素。
源码:

/**
 * Returns a new read-only map with the specified contents, given as a list of pairs
 * where the first value is the key and the second is the value.
 *
 * If multiple pairs have the same key, the resulting map will contain the value from the last of those pairs.
 *
 * Entries of the map are iterated in the order they were specified.
 *
 * The returned map is serializable (JVM).
 *
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V> =
    if (pairs.size > 0) pairs.toMap(LinkedHashMap(mapCapacity(pairs.size))) else emptyMap()

声明:

val name = mapOf<String, String>("name" to "alfred", "sex" to "man", "age" to "27")
Map常用函数

函数

描述

getValue(key)

它返回给定键的值,如果映射中没有这样的键,则抛出异常。

getOrDefault(key,defaultValue)

获取指定key值的value,没有值时返回默认值

contains(key)、containsKey(key)

它检查在Map中是否包含给定的键。

minus(key)

返回去除该 key-value的map

plus(pair)

向map中添加key - value

例:

fun main(args: Array<String>) {
    val name = mapOf<String, String>("name" to "alfred", "sex" to "man", "age" to "27")
    println(name["name"])
    println(name.get("name"))
    println(name.getValue("name"))
    println(name.getOrDefault("weight","70kg"))

    println(name.contains("name"))
    println(name.containsKey("name"))

    println(name.minus("age"))

    println(name.plus("height" to "180cm"))
}

结果:

alfred
alfred
alfred
70kg
true
true
{name=alfred, sex=man}
{name=alfred, sex=man, age=27, height=180cm}

Kotlin MutableMap

MutableMap是集合框架的接口,它以键和值对的形式保存对象。 通过使用相应的键来检索MutableMap接口的值。 键和值可以是不同类型的对,它是可变的。

声明和创建MutableMap

mutableMapOf()声明空的可变map: 该函数返回空的可变的MutableMap集合。
源码:

/**
 * Returns an empty new [MutableMap].
 *
 * The returned map preserves the entry iteration order.
 * @sample samples.collections.Maps.Instantiation.emptyMutableMap
 */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <K, V> mutableMapOf(): MutableMap<K, V> = LinkedHashMap()

声明:

val first = mutableMapOf<String, String>()

mutableMapOf()声明非空的可变map: 该函数返回空的可变的MutableMap集合,接收多个key-value对,这些key-value对将作为Map的元素。
源码:

/**
 * Returns a new [MutableMap] with the specified contents, given as a list of pairs
 * where the first component is the key and the second is the value.
 *
 * If multiple pairs have the same key, the resulting map will contain the value from the last of those pairs.
 *
 * Entries of the map are iterated in the order they were specified.
 *
 * @sample samples.collections.Maps.Instantiation.mutableMapFromPairs
 * @sample samples.collections.Maps.Instantiation.emptyMutableMap
 */
public fun <K, V> mutableMapOf(vararg pairs: Pair<K, V>): MutableMap<K, V> =
    LinkedHashMap<K, V>(mapCapacity(pairs.size)).apply { putAll(pairs) }

声明:

    val name = mutableMapOf<String, String>("name" to "alfred", "sex" to "man", "age" to "27")
MutableMap常用函数

函数

描述

put(key,value)、MutableMap[key]=value

放入key-value对。如果原来已有key,value将被覆盖

putAll(Map)

向原map中添加整个map

remove(key)

删除指定key以及对应value

remove(key, value)

存在键和值实体时,才会删除它们

clear()

删除所有元素

contains(key)、containsKey(key)

检查是否包含给定键,如果map包含指定的键,则返回true

containsValue(value)

如果包含给定值的一个或多个键,则返回true

count()

它返回key-value对的总数

get(key)

返回与键对应的值,如果找不到指定键,则返回null

getOrDefault(key, defaultValue)

返回带有相应指定键的值,如果没有key对应的value,则返回默认值

getValue(key)

返回与给定键对应的值,如果找不到键,则抛出异常

请看下面部分实例:

    val persion = mutableMapOf("name" to "alfred")
    val persion2 = mutableMapOf("sex" to "man", "age" to "27")
    persion.put("身高", "180cm")
    println(persion)

    persion["体重"] = "70kg"
    println(persion)

    persion.putAll(persion2)
    println(persion)

    persion.remove("身高")
    println(persion)

    persion.remove("体重","70kg")
    println(persion)

结果:

{name=alfred, 身高=180cm}
{name=alfred, 身高=180cm, 体重=70kg}
{name=alfred, 身高=180cm, 体重=70kg, sex=man, age=27}
{name=alfred, 体重=70kg, sex=man, age=27}
{name=alfred, sex=man, age=27}
HashMap、LinkedHashMap、TreeMap

声明方式如下:
hashMapOf(): 该函数返回可变的HashMap集合。该函数可接受0个或多个key-value对,这些key-value对将作为Map的元素。
linkedMapOf(): 该函数返回可变的LinkedHashMap集合。该函数可接受0个或多个key-value对,这些key-value对将作为Map的元素。
sortedMapOf(): 该函数返回可变的TreeMap集合。该函数可接受0个或多个key-value对,这些key-value对将作为Map的元素。

可自行查看源码并研究,这儿不再讲述,声明实例如下:

fun main(args: Array<String>) {
    val hash = hashMapOf<String, String>("name" to "alfred")
    val linkedMap = linkedMapOf<String, String>("age" to "27")
    val treeMap = sortedMapOf("sex" to "man")

    println(hash)
    println(linkedMap)
    println(treeMap)
}

结果:

{name=alfred}
{age=27}
{sex=man}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Kotlin 中,`map()` 函数用于将一个列表中的每一个元素映射为另一个值,然后返回一个新的列表。`map()` 函数接受一个 lambda 表达式作为参数,该 lambda 表达式定义了如何将原始列表中的每个元素映射为新的值。 下面是一个简单的示例,假设有一个整数列表,我们想将每个元素乘以 2 并返回一个新的列表: ```kotlin val numbers = listOf(1, 2, 3, 4, 5) val doubledNumbers = numbers.map { it * 2 } println(doubledNumbers) // 输出 [2, 4, 6, 8, 10] ``` 在上面的代码中,我们使用 `map()` 函数将原始列表中的每个元素乘以 2,并得到一个新的列表 `doubledNumbers`。 `map()` 函数的 lambda 表达式可以有一个参数,该参数表示原始列表中当前的元素。如果 lambda 表达式有多个参数,则第一个参数表示原始列表中的当前元素,后面的参数表示其他参数。 例如,如果我们有一个字符串列表,我们可以使用 `map()` 函数将每个字符串转换为大写,并在每个字符串前加上一个前缀: ```kotlin val strings = listOf("hello", "world", "kotlin") val formattedStrings = strings.map { str -> "prefix_$str".toUpperCase() } println(formattedStrings) // 输出 [PREFIX_HELLO, PREFIX_WORLD, PREFIX_KOTLIN] ``` 在上面的代码中,我们首先使用 `map()` 函数将每个字符串转换为大写,并在每个字符串前加上前缀 `prefix_`,然后得到一个新的字符串列表 `formattedStrings`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值