Number of unique characters per line in Scala

I study scala and iterate over some excrement.

So I need to write a function that returns a list of pairs (Char, Int) given by a string as input. I made it work just by experimenting a bit on the scala worksheet.

My solution gives the correct result, I just wonder if it’s good to do it, or maybe there is a better way.

def countChars(s: String): List[(Char, Int)] = {
    s.groupBy(c => c.toLower).flatMap(e => List((e._1, e._2.length))).toList
  }                                              

countChars("Green Grass")

This leads to the same result as on the sheet: res3: List [(Char, Int)] = List ((e, 2), (s, 2), (n, 1), (a, 1), (, 1 ), (g, 2), (g, 2))

+4
source share
4 answers

Creating an alignment-only list is redundant.

"Green Grass".groupBy(c => c.toLower).map(e => (e._1, e._2.length)).toList
+8
source

, - flatMap, . :

import scala.collection.immutable.Map
"Green Grass".map(_.toLower).foldLeft(Map.empty[Char, Int]) { (m, char) =>
  val count = m.getOrElse(char, 0)
  m.updated(char, count+1)
}.toList

, .

+2

A slightly illustrious version of @dhg asnwer:

"Green Grass".groupBy(c => c.toLower).mapValues(group => group.length).toList
+1
source

You can also try this.

def countChars(s: String) =
  s.distinct.map(c => c -> s.count(_ == c))
0
source

Source: https://habr.com/ru/post/1541892/


All Articles