title: trimming all string type columns dynamically of dataframe scala spark
body: <p>Hi I want to trim only string type columns of DF as trimming all columns will change data type of non string column to string type.
  I have 2 ways to do it currently but looking for some good and efficient method.</p>
  <p><strong>First Method</strong></p>
  <pre class="lang-scala prettyprint-override"><code>var Countrydf = Seq((&quot;Virat               &quot;, 18, &quot;RCB ali shah&quot;), (&quot;             Rohit &quot;, 45, &quot;MI &quot;), (&quot; DK&quot;, 67, &quot;KKR &quot;)).toDF(&quot;captains&quot;, &quot;jersey_number&quot;, &quot;teams&quot;)
  
  Countrydf.show
  
  for (name &lt;- Countrydf.schema) {
     if (name.dataType.toString == &quot;StringType&quot;)
       Countrydf = Countrydf.withColumn(name.name, trim(col(name.name)))
   } 
  </code></pre>
  <p><strong>Second Method</strong></p>
  <pre><code>val trimmedDF = Countrydf.columns.foldLeft(Countrydf) { (memoDF, colName) =&gt;
    memoDF.withColumn(colName, trim(col(colName)))
  }
  
  val exprs = Countrydf.schema.fields.map { f =&gt; 
    if (trimmedDF.schema.fields.contains(f)) col(f.name)
    else lit(null).cast(f.dataType).alias(f.name) 
  }
  trimmedDF.select(exprs: _*).printSchema
  </code></pre>
  <p>both works fine and output is same.</p>