Kotlin 将带有可空值的列表转换为不带可空值的 HashMap

Kotlin convert List with nullables to HashMap without nullables

我有传入参数 List<Somedata>
Somedata class 包含 id 字段。

我的目标HashMap<Somedata.id, Somedata> 从这个 list.

下一个方法是正确的还是有 better/safer 方法来做到这一点?

list
    .filter { it.id != null }
    .associateTo(HashMap(), {it.id!! to it})

其实我不明白,为什么我要在associateTo方法中使用!!关键字,上面我只用非空值过滤它。

或者也许有使用 ?.?.let 关键字执行此操作的好方法?

你可以这样做:

list.mapNotNull { e -> e.id?.let { it to e } }.toMap()

细分:

如果元素为空,使用 ?. 安全调用运算符对 .let 的调用将使结果为 null

所以传递给 mapNotNull 的 lambda 是 (Somedata) -> Pair<IdType, Somedata>.

类型

mapNotNull 丢弃 null 对,toMap 将结果 List<Pair<IdType, Somedata>> 变成 Map<IdType, Somedata>.

如果你想避免创建一个中间列表来保存对,你可以从一开始就把列表变成惰性的Sequence

list.asSequence().mapNotNull { e -> e.id?.let { it to e } }.toMap()

或者,既然你问了:

why should I use !! keyword in associateTo method, when above I filtered it with non-null values only.

这是因为列表仍然是 List<Somedata> 类型 - 这没有说明 字段 本身的可空性。在执行 associateTo 调用时,编译器不知道 id 字段 仍然 不为空。