Search code examples
scalahashmaplistbuffer

Gather keys from multi level Hashmaps to an Ordered ListBuffer in Scala


I have a Hashmap say H1, with the following components :

H1:
Key1: Int
Value1: Hashmap H2

H2:
Key2: Int
Value2 : Objects of multiple types

My target is to gather all keys of H2s in H1 in an ordered Listbuffer (distinct values) the fastest way possible.

Example :

(35->((3->obj1),(4->obj2)), 
36->((4->obj3),(6->obj4)), 
37->((5->obj5),(3->obj6)))

I would have a ListBuffer(3,4,5,6) and H1 might grow relatively big.


Solution

  • This should work:

    h1Map
      .valuesIterator
      .flatMap(_.keysIterator)
      .distinct
      .toList
      .sorted
    

    If you really need a mutable ListBuffer you can change the toList with to[ListBuffer] (if you are in 2.12-) or to(ListBuffer) (if you are in 2.13+).
    However, I would recommend you to try to avoid mutable collections and stick with immutable ones.