3

I have two vals:

// 0~250::250~500::500~750::750~1000
val step_x_ranges = stepsAsString.mkString("::")

// 1::22::7::16
val step_y = histogram_final.map{case (x , y) => y}.mkString("::")

And I want to save it to an Array like:

0~250::1
250~500::22
500~750::7
750::1000::16

But still not try out: Please help me

Here is my wrong code:

var toArray : Array[String] = Array()
   for (i <- 0 to 3)
   {
     val ArrayRow = step_x_ranges(i) + "::" + step_y(i)
     toArray = toArray :+ ArrayRow
   }
   println(toArray(0)) 
   println(toArray(1))

Result:

0::4
~::8 
1

1 Answer 1

3

Use zip:

scala> val step_x_ranges = Array("0~250", "250~500", "500~750","750~1000")
step_x_ranges: Array[String] = Array(0~250, 250~500, 500~750, 750~1000)

scala> val step_y = Array(1, 22, 7, 16)
step_y: Array[Int] = Array(1, 22, 7, 16)

scala> val result = step_x_ranges.zip(step_y).map{case (x, y) => s"$x::$y"}
res1: Array[String] = Array(0~250::1, 250~500::22, 500~750::7, 750~1000::16)
scala> scala.tools.nsc.io.File("test.txt").writeAll(result.mkString("\n"))

And test.txt:

0~250::1
250~500::22
500~750::7
750~1000::16
Sign up to request clarification or add additional context in comments.

5 Comments

You are right! I get Vector(0~250::1, 250~500::22, 500~750::7, 750~1000::16) But how can I save this to a txt file ? ```` 0~250::1 250~500::22 500~750::7 750::1000::16````
I added saving to file to my answer. Use` mkString(" ")` if you need saving in one row.
I met an error :Exception in thread "main" java.lang.NoClassDefFoundError: scala/reflect/io/AbstractFile$ Do you know this?
@user2492364, scala or Spark version mismatch, maybe?
@Paul has a good idea. IIn addition if you use spark and your data is rdd, then you should use result.saveAsTextFile("pathToFile"). Anyway there is not enough information about your problem, you would better create another example with your configs.

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.