val filename = “gh_emails_sorted.txt”
var hash = new HashMap()
for (line ← Source.fromFile(filename).getLines) {
val x = line.stripLineEnd.split("@")
val dom = x(1)
if (hash.contains(dom)) hash(dom) += 1 else hash(dom) = 1
}
It can’t work at all.
Yes I know I have less experience on scala’s collection.
Can you help me with my issue?
Why are you using the HashMap, or want to do it using hashMap, when you can use the “distinct” method that can provide you this result quickly and efficiently?
It has 7 emails but 5 unique domains.
Now I have the file count.scala:
import scala.io.Source
val filename = "emails.txt"
val file = Source.fromFile(filename)
val emails =
for
line <- file.getLines
yield
line.split("@")(1)
emails.distinct.size
I load these into the REPL:
scala> :l count.scala
val filename: String = emails.txt
val file: scala.io.BufferedSource = <iterator>
val emails: Iterator[String] = <iterator>
val res4: Int = 5
Not sure if this is idiomatic Scala or the best/most efficient way to do it, but it’s just another way! Hopefully you find it useful!
Oh right, my fault actually for not replying to you.
Also, you are right the problem description says one thing and the code tries to do another. Not sure which one is what OP really needs. In the case they only need to know how many different domains there are, then yeah your solution is pretty good; I personally would use map instead of for but that is just a style thing.