title: Taking first element of a GroupedObservable with RxJava
body: <p>I'm pretty new to RxJava.</p>
  
  <p>I'm trying to group elements by a given key and take the first value of each key.</p>
  
  <p>For instance, group these names by their first letter and print the first one for each group:</p>
  
  <pre><code>Observable&lt;String&gt; names = Observable.just(
                               "John", "Steve", "Ruth",
                               "Sam", "Jane", "James");
  </code></pre>
  
  <p>Here's what I tried so far :</p>
  
  <p><strong>1st try</strong>:</p>
  
  <pre><code>names.groupBy(s -&gt; s.charAt(0))
       .flatMap(grp -&gt; grp.first())
       .subscribe(s -&gt; System.out.println(s));
  </code></pre>
  
  <p><em>FAILED!</em>: all the names are printed.</p>
  
  <p><strong>2nd try</strong>:</p>
  
  <pre><code>names.groupBy(s -&gt; s.charAt(0))
       .subscribe(grp -&gt; grp
                           .first()
                           .subscribe(System.out::println));
  </code></pre>
  
  <p><em>FAILED AGAIN!</em>: all the names are still printed...</p>
  
  <p>I managed to get the expected result by reducing each GroupedObservable :</p>
  
  <p><strong>1st try, with reduce</strong>:</p>
  
  <pre><code>names.groupBy(s -&gt; s.charAt(0))
       .flatMap(grp -&gt; grp.reduce((a, b) -&gt; a))
       .subscribe(s -&gt; System.out.println(s));
  </code></pre>
  
  <p><strong>2nd try, with reduce</strong>:</p>
  
  <pre><code>names.groupBy(s -&gt; s.charAt(0))
       .subscribe(grp -&gt; grp
                           .reduce((a, b) -&gt; a)
                           .subscribe(System.out::println));
  </code></pre>
  
  <p>But this solution is not ideal. In a real world situation, this would involve some expensive computation and the <code>reduce()</code> operator would take a lot longer to compute (computing all the values) than the <code>first()</code> operator (computing only 1 value by key).</p>