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)
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
NikRED
  • 1,175
  • 2
  • 21
  • 39

4 Answers4

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
Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
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.

Mario Galic
  • 47,285
  • 6
  • 56
  • 98
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.

naval jain
  • 353
  • 3
  • 4
  • 14
  • You can also append flatten at the end to get list of strings. words.map(line=>line.split("_").toList).flatten – naval jain Sep 14 '19 at 11:02
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)
jq170727
  • 13,159
  • 3
  • 46
  • 56