如何使用scala上的映射删除空字符串/ null?

时间:2016-02-29 02:49:05

标签: scala filter null

 <?php
$scale = array(
"A" => "Do",
"B" => "Re",
"C" => 'Mi',
"D" => 'Fa',
"E" => 'So',
"F" => 'La',
"G" => 'Ti'
);


if (isset($_POST['notes']))
 {
   $query=$_POST['notes'];
   foreach ($scale as $key => $sound)
   {
    if ($query == $key)  
    {
        echo $sound;
    }
    }
    }


 ?>

<form action="MusicalScale.php" method="post">

<label>Enter in a music note</label>&nbsp;&nbsp;<input type="text"    name="notes"><br>
<input type="submit" value="Submit">

</form>

我只需要映射那些p(14)不为空的行。我如何在scala上执行此操作?

3 个答案:

答案 0 :(得分:0)

val labResult = RDDlab.filter(p => p(14).toString != null && !p(14).toString.isEmpty).map(p => LabResult(p(1).toString, dateFormat.parse(p(8).toString), p(7).toString, p(14).toString.toDouble))

用户filter即可。

答案 1 :(得分:0)

我建议在这里使用StringUtils来过滤掉空字符串和空字符串。

import org.apache.commons.lang3.StringUtils
val labResult = RDDlab.filter(p => StringUtils.isNotEmpty(p(14).toString)).map(p => LabResult(p(1).toString, dateFormat.parse(p(8).toString), p(7).toString, p(14).toString.toDouble))

答案 2 :(得分:0)

对于此Scala提供了collect方法,该方法可以与pattern matchingpattern guards巧妙地结合使用。

val labResult = 
  RDDlab
    .collect{
       case p if p(14) != null && p(14).toString.isDefined =>
         LabResult(
           p(1).toString,
           dateFormat.parse(p(8).toString),
           p(7).toString,
           p(14).toStr
         )
     }