0

I have a List[(Int,Int)]

such that

{(1,5),(1,2),(1,7),(2,8),(2,3),(2,9),(3,10),(3,1),(3,12)}

What I want to do is to apply sum on every 2nd element of each (1,5),(1,2),(1,7)

2nd element of each (2,8),(2,3),(2,9)

and each (3,10),(3,1),(3,12)

such that we have a resultant:

List[Int]={14, 20, 23}

2 Answers 2

3

use grouped to split list by size, map the second value and sum, like:

list.grouped(3).map(_.map(_._2).sum).toList
> List(14, 20, 23)
Sign up to request clarification or add additional context in comments.

3 Comments

thanx for consideration
@AqsaZahoor approve the answers if they answer your question - stackoverflow.com/help/someone-answers
if i want to apply any other operation than sum i.e a function then this will not work
1

You might group them by the 1st element of the tuple. Then you'll have a Map with a key for every distinct 1st element and a List of all the associated 2nd elements.

val myMap = myList.groupBy(_._1).mapValues(_.map(_._2))

Now you can sum the 2nd elements or apply any other transformation operation desired.

val mySums = myMap.mapValues(_.sum)  //Map(2 -> 20, 1 -> 14, 3 -> 23)

And you can extract them in some desired order.

mySums.keys.toList.sorted.map(mySums)  //res0: List[Int] = List(14, 20, 23)

Comments

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.