0

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(";")
1
  • .toList? should work Commented May 19, 2020 at 8:53

1 Answer 1

1

You can use collect

  List("a", "b", "c").collect {
    case c if StringUtils.isNotBlank(c) => c
    case _ => "-"
  }.mkString(";")
Sign up to request clarification or add additional context in comments.

3 Comments

In case I do not have a blank value check , is there any alternative to collect
if you don't do any checks, there is no point in foldLeft , this will be sufficient List("a", "b", "c").mkString(";")
Since you never drop any elements, I think map instead of collect will suffice here.

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.