Goltsev Eugene
Goltsev Eugene

Reputation: 3627

Kotlin convert List with nullables to HashMap without nullables

I have incoming param List<Somedata>.
Somedata class contains id field.

My goal is to make HashMap<Somedata.id, Somedata> from this list.

Is next approach correct or there is a better/safer way to do that?

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

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

Or maybe there is a good way to perform this with ?. or ?.let keywords?

Upvotes: 2

Views: 1830

Answers (1)

Salem
Salem

Reputation: 14907

You can do:

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

Breakdown:

The call to .let with the ?. safe call operator will make the result null if the element is null.

So the lambda passed to mapNotNull is of type (Somedata) -> Pair<IdType, Somedata>.

mapNotNull discards the null pairs, and toMap turns the resulting List<Pair<IdType, Somedata>> into a Map<IdType, Somedata>.

If you want to avoid the creation of an intermediate list to hold the pairs, you can turn the list into a lazy Sequence from the start:

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

Alternatively, since you asked:

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

this is because the list is still of type List<Somedata> - this says nothing about the nullability of the field itself. The compiler does not know that the id fields are still not null, by the time your associateTo call is executed.

Upvotes: 8

Related Questions