Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending to Map with value as a list

Tags:

scala

I have initialized a mutable Map (not sure if I should use a mutable here, but to start with I use mutable):

val aKey = "aa"
val myMap = scala.collection.mutable.Map[String, List[String]]()
if (myMap.exists(_._1 == aKey))
    myMap(aKey) = myMap.get(aKey) :: "test"

But on myMap.get(aKey) I get the following error:

Type Mismatch expected List[String] actual option[String]

I thought the way I did is correct to append to list.

like image 812
add-semi-colons Avatar asked Jun 18 '15 15:06

add-semi-colons


People also ask

Can a map value be a List?

The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed: List of values and. List of keys from a Map.

Can we add List to map in Java?

From Java 8 onwards, we can convert List to Map using the stream() and the Collectors. toMap() methods. The toMap() method will return a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

How do I put multiple values on a map?

If this is an application requirement, the three best ways to solve the 'multiple values per key in a map in Java' problem are: Stick with the standard APIs and add a collection class like a 'Vector' or 'ArrayList' to your map or set. Use the MultiMap and MultiValueMap classes from the Apache Commons library.


2 Answers

You can append to a mutable map with +=.

scala> myMap += ("placeholders" -> List("foo", "bar", "baz"))
res0: scala.collection.mutable.Map[String,List[String]] = Map(placeholders -> List(foo, bar, baz))

To append a new item to the list for aKey as mentioned in the commments.

myMap.get("placeholders") match {
 case Some(xs:List[String]) => myMap.update("placeholders", xs :+ "buzz")
 case None => myMap
}
res22: Any = ()

scala> myMap
res23: scala.collection.mutable.Map[String,List[String]] = Map(placeholders -> List(foo, bar, baz, buzz))
like image 76
Brian Avatar answered Oct 13 '22 13:10

Brian


If you have mutable Map and inside that map immutable List. This is a simple example on how to do it. The example is also defining using withDefaultValue - so that you always get something back from Map.

var posts: collection.mutable.Map[Int, List[String]] = collection.mutable.Map().
  withDefaultValue List.empty[String]

def addTag(postID: Int, tag: String): Unit = posts.get(postID) match {
  case Some(xs: List[String]) => posts(postID) = xs :+ tag
  case None => posts(postID) = List(tag)
}

posts(42)
// List[String] = List() 

addTag(42, "tag-a")
addTag(42, "tag-b")
addTag(42, "tag-c")

posts(42)
// List[String] = List(tag-a, tag-b, tag-c)
like image 29
Oto Brglez Avatar answered Oct 13 '22 12:10

Oto Brglez