coder25
coder25

Reputation: 2393

How to convert ListBuffer to List (immutable collection ) in scala

I have the below code using ListBuffer but I want to use immutable collection like List and achieve the same result

val list1: ListBuffer[String] = ListBuffer("a", "b", "c")
val s= list1
    .foldLeft(mutable.ListBuffer.empty[String]) { (strings, content) =>
      {
        if(StringUtils.isNotBlank(content))
          strings += content
        else
          strings += "-"

      }
    }
    .mkString(";")

Second version

val list1: ListBuffer[String] = ListBuffer("a", "b", "c")
val s= list1
    .foldLeft(mutable.ListBuffer.empty[String]) { (strings, content) =>
      {

       strings += content

      }
    }
    .mkString(";")

Upvotes: 0

Views: 2143

Answers (1)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

You can use collect

  List("a", "b", "c").collect {
    case c if StringUtils.isNotBlank(c) => c
    case _ => "-"
  }.mkString(";")

Upvotes: 1

Related Questions