yoru yoru - 10 months ago 36
Scala Question

Want to make output as an Object instead of println

I want to make an object instead of println.

text file would be like






and result like





def main(args: Array[String]) = {

val conf = new SparkConf()
val sc = new SparkContext(conf)

// read text info
val textfile = sc.textFile("C:\\fruitbox.csv")
val map = twitter.map { word => (word, 1) }
.reduceByKey(_ + _)
.foreach(println) // ← want to do something about this row

but I want to make println result to be like this


it seems like simple knowledge of syntax
but I couldn't figure this out.

Answer Source

You need to think of it in functional terms or you will get crazy. Replace the foreach with a map that takes a function of this form:


Do you know case classes? If you don't, you should give it a look and define your own to hold the data you deal with. Otherwise, if you want to build a specific instance of an already existing class that has setters, you can do it this way:

val myInstance = new myClass()

Mind the brackets: {} these define a scope where you can write non-functional code and the last value of this scope will be the value returned, in this case the instance of your class.

Also when you post stuff about Spark, try to make explicit the types you're dealing with at every step so it's easier to write code to help you.