title: Iterate through a Java RDD by row
body: <p>I would like to iterate through an RDD of strings and "do something" to each string. The output should be <code>double[][]</code>. Here is an example with a for loop. I understand I need to use (I think) the <code>foreach</code> function for Java RDDs. However, I have no idea how to understand the syntax. Documentation is not particularly helpful. I do not have Java 8.</p>
  
  <p>Here is an example of what I would like to do if I could use a regular <code>for</code> loop.</p>
  
  <pre><code>public class PCA {
  
      public static void main(String[] args) {
          SparkConf conf = new SparkConf().setAppName("PCA Example");
          SparkContext sc = new SparkContext(conf);
  
          RDD&lt;String&gt; data = sc.textFile("my/directory/my/dataset.txt", 0);
  
          // here is the "type" of code I would like to execute
          // 30 because I have 30 variables
          double[][] vals = new double[data.count()][30];
  
          double[] temp;
          for (int i = 0; i &lt; data.count(); i++) {
              temp = splitStringtoDoubles(data[i]);
              vals[i] = temp;
          }
      }
  
      private static double[] splitStringtoDoubles(String s) {
          String[] splitVals = s.split("\\t");
          Double[] vals = new Double[splitVals.length];
          for (int i = 0; i &lt; splitVals.length; i++) {
              vals[i] = Double.parseDouble(splitVals[i]);
          }
      }
  
  }
  </code></pre>
  
  <p>I understand that <code>foreach</code> seems to require a function that has a void return type. Not sure how to work with that. Here is what I have attempted so far (obviously the syntax is wrong):</p>
  
  <pre><code>    double[][] matrix = new double[data.count()][30];
      foreach(String s : data) {
          String[] splitvals = s.split("\\t");
          double[] vals = Double.parseDouble(splitvals);
          matrix[s] = vals; 
      }
  </code></pre>