title: Extract only certain columns in Java Spark
body: <p>I have a file with 10 columns. What's the most elegant way to extract only first 3 columns or specific columns?</p>
  
  <p>For example, this is how my file looks like:</p>
  
  <pre><code>john,smith,84,male,kansas
  john,doe,48,male,california
  tim,jones,22,male,delaware
  </code></pre>
  
  <p>And I want to extract into this:</p>
  
  <pre><code>[john, smith, kansas]
  [john, doe, california]
  [tim, jones, delaware]
  </code></pre>
  
  <p>What I have is this, but it doesn't specifically chose the columns that I want:</p>
  
  <pre><code>JavaRDD&lt;String&gt; peopleRDD = sc.textFile(DATA_FILE);
  peopleRDD.cache().map(lines -&gt; Arrays.asList(lines.split(",")))
                   .forEach(person -&gt; LOG.info(person));
  </code></pre>
  
  <p>I read the <a href="https://stackoverflow.com/questions/32396379/how-to-select-3-columns-from-csv-file-using-java-spark-coding-also-group-by-and">following</a> <a href="https://stackoverflow.com/questions/26821707/read-column-from-csv-with-java-spark">two</a> Stackoverflow posts but I still can't decide how to do this.</p>
  
  <p><strong>EDIT:</strong>
  I ended up doing the following:</p>
  
  <pre><code>JavaRDD&lt;String&gt; peopleRDD = sc.textFile(DATA_FILE);
      peopleRDD.cache().map(lines -&gt; Arrays.asList(new String[]{lines.split(",")[0], 
                                                          lines.split(",")[1], 
                                                          lines.split(",")[3]}
                       .forEach(person -&gt; LOG.info(person));
  </code></pre>
  
  <p>Not the most elegant solution but if you have a better way, please post here. Thanks.</p>