0

I have a List of Lists in Scala, that looks likes this: List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10), I want to convert it into a HashMap[Int, List[Int]] where the first Int is the index of each list and the List[Int] is the list itself. In the end the HashMap should look like

 HashMap[Int, List[Int]](
      0 -> List(1, 5, 6, 10),
      1 -> List(1, 6),
      2 -> List (1, 3, 10),)

Here's my approach, have a list 0 to the length of the list and zip it with this nested list, then somehow convert it into a HashMap. But I'm looking for something more idiomatic or neater. Any ideas?

1 Answer 1

3

A zipWithIndex with a map should do it:

scala> val a = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))
a: List[List[Int]] = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))

scala> a.zipWithIndex.map(_.swap).toMap
res0: scala.collection.immutable.Map[Int,List[Int]] = 
Map(
    0 -> List(1, 5, 6, 10),
    1 -> List(1, 6), 
    2 -> List(1, 3, 10)
)

Edit:

If you absolutely need a HashMap, things are a little messier:

scala> val a = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))
a: List[List[Int]] = List(List(1, 5, 6, 10), List(1, 6), List(1, 3, 10))

scala> val b = a.zipWithIndex.map(_.swap)
b: List[(Int, List[Int])] = List((0,List(1, 5, 6, 10)), (1,List(1, 6)), (2,List(1, 3, 10)))

scala> val hM = collection.immutable.HashMap[Int, List[Int]](b: _*)
hM: scala.collection.immutable.HashMap[Int,List[Int]] = 
Map(
    0 -> List(1, 5, 6, 10),
    1 -> List(1, 6),
    2 -> List(1, 3, 10)
)
Sign up to request clarification or add additional context in comments.

4 Comments

use _.swap instead of x => (x._2, x._1)
Added, I'll have to remember that!
Very nice. Is there any way to convert it into a HashMap instead of a Map. My function is complaining expected HashMap[Int, List[Int]], actual: Map[Int, List[Int]].
@TeodoricoLevoff see my edit for HashMap conversion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.