Kotlin将带有nullables的List转换为没有nullables的HashMap

问题描述 投票:2回答:1

我有传入的param List<Somedata>Somedata类包含id字段。 我的目标是从这个HashMap<Somedata.id, Somedata>制作list

下一步方法是正确的还是有更好/更安全的方法来做到这一点?

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

实际上,我无法理解,为什么我应该在!!方法中使用associateTo关键字,在上面我只用非空值过滤它。

或者也许有一个很好的方法来执行?.?.let关键字?

collections kotlin nullable
1个回答
7
投票

你可以做:

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

分解:

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

因此传递给mapNotNull的lambda是(Somedata) -> Pair<IdType, Somedata>类型。

mapNotNull丢弃空对,而toMap将得到的List<Pair<IdType, Somedata>>变成Map<IdType, Somedata>

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

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

或者,因为你问:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.