Frage

I have a Tuple of type :

val data1 : (String , scala.collection.mutable.ArrayBuffer[(String , Int)]) = ( ("" , scala.collection.mutable.ArrayBuffer( ("a" , 1) , ("b" , 1) , ("a" , 1) ) ))  // , ("" , scala.collection.mutable.ArrayBuffer("" , 1)) )

When I attempt to map using : data1.map(m => println(m)) I receive error :

Multiple markers at this line - value map is not a member of (String, scala.collection.mutable.ArrayBuffer[(String, 
 Int)]) - value map is not a member of (String, scala.collection.mutable.ArrayBuffer[(String, Int)])

Is it possible to use map function using Tuple accessor syntax : ._2 ?

This type of syntax data1.map(m._2 => println(m._2))) does not compile

Using this syntax I'm attempting to apply a map function to sum all the letters associated with the ArrayBuffer. So above example should map to -> ( (a , 2) , (b , 1) )

War es hilfreich?

Lösung

Its unclear what you want. What output are you expecting?

Do you want to print the second item of data1?

println(data1._2)

Or print each item of the buff in data1?

data1._2.foreach(m => println(m))

Do you want for data1 to be a collection of tuples and to map over that?

import scala.collection.mutable.ArrayBuffer
val data1 = Vector(("" , ArrayBuffer(("", 1))), ("", ArrayBuffer("", 1)))
data1.foreach { case (a,b) => println(b) }

Note that if you're just printing stuff out, you want foreach, not map.



Based on your edits:

import scala.collection.mutable.ArrayBuffer
val data1 = (("", ArrayBuffer(("a", 1), ("b", 1), ("a", 1))))
val grouped = data1._2.groupBy(_._1).map { case (k, vs) => (k, vs.map(_._2).sum) }
// Map(b -> 1, a -> 2)

Andere Tipps

You can't use map on tuples. Tuples don't have such method.

Also map function should transform value and return it, but you just want to print it, not change.

To print ArrayBuffer in your case try this:

data1._2.foreach(x=>println(x))

or just

data1._2.foreach(println)

Try

data1.foreach( { case ( x, y ) => println( y ) } )
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top