From 2 lists of the form List[(Int, String)
:
l1 = List((1,"a"),(3,"b"))
l2 = List((3,"a"),(4,"c"))
how can I combine the Integer
s where the String
s are the same to get this third list:
l3 = List((4,"a"),(3,"b"),(4,"c"))
Right now I'm traversing both of the lists and adding if the strings are the same, but I think there should be a simple solution with pattern matching.
By using ::: If we using the List class frequently, we may prefer using ::: method. Example: Scala.
Syntax for defining a Scala List. val variable_name: List[type] = List(item1, item2, item3) or val variable_name = List(item1, item2, item3) A list in Scala is mostly like a Scala array. However, the Scala List is immutable and represents a linked list data structure. On the other hand, Scala array is flat and mutable.
Use the sortWith() Function to Sort List in Scala. We used the sortWith() function to take a lambda expression as an argument and return the sorted result. We can use this function to sort the list in ascending and descending order.
If you want to use the add operation, you would have to declare an ArrayList. Vals in scala are essentially immutable, so you can't add to them. iirc val is more like final, you can add to them if you use the mutable Collections.
val l = l1 ::: l2
val m = Map[String, Int]()
(m /: l) {
case (map, (i, s)) => { map.updated(s, i + (map.get(s) getOrElse 0))}
}.toList // Note: Tuples are reversed.
But I suppose there is a more elegant way to do the updated
part.
How about,
(l1 ++ l2).groupBy(_._2).mapValues(_.unzip._1.sum).toList.map(_.swap)
Unpacking this a little on the REPL helps to show what's going on,
scala> l1 ++ l2
res0: List[(Int, java.lang.String)] = List((1,a), (3,b), (3,a), (4,c))
scala> res0.groupBy(_._2)
res1: ... = Map(c -> List((4,c)), a -> List((1,a), (3,a)), b -> List((3,b)))
scala> res1.mapValues(_.unzip)
res2: ... = Map(c -> (List(4),List(c)), a -> (List(1, 3),List(a, a)), b -> (List(3),List(b)))
scala> res1.mapValues(_.unzip._1)
res3: ... = Map(c -> List(4), a -> List(1, 3), b -> List(3))
scala> res1.mapValues(_.unzip._1.sum)
res4: ... = Map(c -> 4, a -> 4, b -> 3)
scala> res4.toList
res5: List[(java.lang.String, Int)] = List((c,4), (a,4), (b,3))
scala> res5.map(_.swap)
res6: List[(Int, java.lang.String)] = List((4,c), (4,a), (3,b))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With