0

I am trying to understand the output which i got from below code, It shows some alpha numeric values prefix with @. how can i change it to ("Hello,world"),("How,are,you")

Scala Code:

val words = List("Hello_world","How_are_you" )
val ww= words.map(line=>line.split("_"))
println(ww)

output

List([Ljava.lang.String;@7d4991ad, [Ljava.lang.String;@28d93b30)

4 Answers 4

6

Add .toList

val ww = words.map(line=>line.split("_").toList)
// List(List(Hello, world), List(How, are, you))
ww == List(List("Hello", "world"), List("How", "are", "you")) // true

Otherwise ww is a List[Array[String]] rather than List[List[String]] and println shows hashcodes of arrays.

Or maybe you're looking for

val ww1 = words.map(_.replace("_", ","))
// List(Hello,world, How,are,you)
ww1 == List("Hello,world", "How,are,you") // true
Sign up to request clarification or add additional context in comments.

3 Comments

OP needs .flatMap.
@GeorgeLeung words.flatMap(line=>line.split("_").toList) produces List(Hello, world, How, are, you). But Op wanted ("Hello,world"),("How,are,you") whatever this means.
Oh you’re right, I misread. Probably because I didn’t see nested brackets in the question.
4

To prettify Array printing consider ScalaRunTime.stringOf like so

import scala.runtime.ScalaRunTime.stringOf
println(stringOf(ww))

which outputs

List(Array(Hello, world), Array(How, are, you))

As explained by @Dmytro, Arrays are bit different from other Scala collections such as List, and one difference is they are printed as hashCode representations

public String toString() {
  return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

instead of value representations.

Comments

2

The output here is as expected. It just printed out the list with fully qualified name for the corresponding string with @ hashcode. Standard in most of the JVM languages.

1 Comment

You can also append flatten at the end to get list of strings. words.map(line=>line.split("_").toList).flatten
1

Perhaps mkString is what you are looking for?

scala> val ww2 = words.map(line=>line.split("_").mkString(","))
ww2: List[String] = List(Hello,world, How,are,you)

scala> println(ww2)
List(Hello,world, How,are,you)

Comments

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.