简体   繁体   中英

Combining elements in a Scala list

How do I combine elements in a list, eg

List(('h', 1), ('i', 1), ('h', 1), ('i', 1), ('l', 2))

such that I get the following result:

List(('h', 2), ('i', 2), ('l', 2))

Basically, I want to sum the numbers associated with each letter, and the letter should appear in the list only once.

val myList = List(('h', 1), ('i', 3), ('h', 5), ('i', 7), ('l', 2))
myList.groupBy(_._1).mapValues(_.foldLeft(0)(_ + _._2)).toList
res0: List[(Char, Int)] = List((h,6), (i,10), (l,2))
val df = List(('h', 1), ('i', 1), ('h', 1), ('i', 1), ('l', 2))
val c = df.groupBy(_._1).mapValues(_.map(_._2).sum).toList
List((h,2), (i,2), (l,2))

you can do:

val h = List(('h', 3), ('i', 1), ('h', 1), ('i', 1), ('l', 2))

h.groupBy(_._1).map(f => (f._1, f._2.map(_._2).sum)).toList

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