简体   繁体   中英

How to access Tuples of a List in a Map in Scala?

I have a map of format

scala.collection.mutable.Map[String,List[(Int, Int, Int)]]

and I want to be able to access the individual Int's. The format of the data to go in the Map will always be

Mon-18-June-2018,1:10:5,2:20:10,3:30:15,4:40:20,5:50:25

Where the date is the key of the Map and each set of three numbers is the (Int, Int, Int)

So far, I have been able to print the Map in this format

Mon-18-June-2018
List((1,10,5), (2,20,10), (3,30,15), (4,40,20), (5,50,25))

Using the below code

map.keys.foreach{i =>
    println(i)
    println(map(i))    

I would like to be able to access the individual values in the tuples. For example, I would like to be able to add every 2nd and 3rd value of each tuple together
(1,10,5)
(2,20,10)
(3,30,15)
(4,40,20)
(5,50,25)

to get
(6,150,75)

How do I do this?

You can use pattern matching to access elements of the tuple.

val dateMap :Map[String,List[(Int, Int, Int)]] =
  Map("Mon-18-June-2018" ->
    List((1,10,5), (2,20,10), (3,30,15), (4,40,20), (5,50,25)))

dateMap.values.map(_.fold((1,0,0)){case ((a,b,c),(x,y,z)) => (a+1,b+y,c+z)})
//res0: Iterable[(Int, Int, Int)] = List((6,150,75))

The easiest way is:

val yourMap : Map[String,List[(Int, Int, Int)]] = Map("Mon-18-June-2018" -> List((1,10,5), (2,20,10), (3,30,15), (4,40,20), (5,50,25)))
yourMap.map(x=> (x._2.length+1,x._2.map(_._2).sum,x._2.map(_._3).sum))

you can find more forms here: Scala: How to sum a list of tuples

To get each individual value in a List, you could .map inside it.

To get each element of a Tuple, use tuple._1 , tuple._2 , tuple._3 , and so on.

In your case, to add all of the values of the Tuples together you can do something like this:

val m = scala.collection.mutable.Map[String,List[(Int, Int, Int)]](
  "Mon-18-June-2018" -> List((1, 10, 5), (2, 20, 10), (3, 30, 15), (4, 40, 20), (5, 50, 25))
)

m.map {
  // get keys and values
  case (k, v) =>
    // construct a Tuple of all of the sums
    (v.map(_._1).sum, v.map(_._2).sum, v.map(_._3).sum)
}
// ArrayBuffer((15,150,75))

This will create a List of Tuples ( (Int, Int, Int) ), where each Tuple corresponds to a key in the original Map. You could even keep the original Map's keys by doing something like this:

m.map{
  // get keys and values
  case (k, v) =>
    // "x -> y" creates a Tuple, or in this case a Map
    k -> (v.map(_._1).sum, v.map(_._2).sum, v.map(_._3).sum)
}
// Map(Mon-18-June-2018 -> (15,150,75))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM