Scala List mkString() with examples

 263 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about the Scala List mkString() operation with examples. There is an alternative to mkString() operation in Scala, please have a look at addString()

List() is a collection to store values in an ordered fashion.

mkString() is the most useful method of a Scala collection which allows generating a string based on the elements of the collection. When mkString() is applied on a list or collection, it returns a string by concatenation of all elements of the collection.

There are three variants of mkString() operation

  1. mkString() without separator.
  2. mkString() with separator.
  3. mkString() with start,separator and end.

Let us see an example of each variant.

mkString() – without separator example

This variant of mkString() operation allows us to displays all elements of the collection in a string.

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

    //create a List
    var list: List[String] = List("a", "b", "c", "d", "a", "c") //Without seperator
    
    //Apply mkString
    println(list.mkString)
  }
}

Output

abcdac

mkString() – with separator example

This variant of mkString() operation allows us to displays all elements of the collection with a separator in a string.

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

    //create a List
    var list: List[String] = List("a", "b", "c", "d", "a", "c")
    
    //Apply mkString
    println(list.mkString("-")) //with separator
  }
}

Output

a-b-c-d-a-c

mkString() – with start,separator and end example

This variant of mkString() operation allows us to displays all elements of the collection with a separator, start and end Strings in a string.

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

    //create a List
    var list: List[String] = List("a", "b", "c", "d", "a", "c")

    //Apply mkString
    println(list.mkString("/", "-", ";")) //With start,separator and end
  }
}

Output

/a-b-c-d-a-c;

ReferencesScala List mkString operation

I hope you like this tutorial and you were able to understand Scala list mkString operation with examples.

Thanks for reading and please give us a thumb up and comment below.

 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.