Filter and process hashmap entries in Kotlin

I probably miss something very obvious: how to efficiently filter and iterate over entries in the HashMap in Kotlin?

I want to do the following:

myMap.filterValues{ someCondition }.forEach { doSomethingWithTheEntry }

How can I avoid creating intermediate objects? filterValues ​​will create a HashMap that is not needed here.

I could certainly write

myMap.forEach { if(someCondition) doSomethingWithTheEntry }

but the filter style approach with a functional style looks more elegant.

+4
source share
1 answer

To avoid storing intermediate values, you can use Sequencewhat is somewhat lazy equivalent Iterable(see another Q & A question ).

a Map Sequence, .asSequence() ( , ), .filter { ... } .forEach { ... } :

myMap.asSequence().filter { someCondition(it) }.forEach { doSomething(it) }

, , , , , .

, , , Sequence : , , .

+5

Source: https://habr.com/ru/post/1694471/


All Articles