Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The monadic approach to this problem is to define an operation that transforms an iterable into an iterable of iterables, by defining a transformation function that for an object of type <code>T</code>, returns an object of type <code>Iterable&lt;T&gt;</code>. You can then concatenate each iterable to form a single one again. This combination of a mapping followed by a concatenation is called <code>concatMap</code> in Haskell and <code>flatMap</code> in Scala, and I'm sure it has other names elsewhere.</p> <p>To implement this, we first create a function that transforms your <code>S&lt;? extends Number&gt;</code> into <code>Iterable&lt;S&lt;Double&gt;&gt;</code>. This is very similar to your existing function, but our success case is an iterable of one, containing our <code>S</code>, and the failure case (our null state) is an empty iterable.</p> <pre><code>&lt;T extends Number&gt; Function&lt;S&lt;?&gt;, Iterable&lt;S&lt;T&gt;&gt;&gt; castOrNull(Class&lt;T&gt; type) { return new Function&lt;S&lt;?&gt;, Iterable&lt;S&lt;T&gt;&gt;&gt; { @Override public Iterable&lt;S&lt;T&gt;&gt; apply(S&lt;?&gt; s) { Object contained = s.get(); if (!(contained instanceof T)) { return ImmutableSet.of(); } return ImmutableSet.of(new S&lt;T&gt;(contained)); } }; } </code></pre> <p>We then apply this to the original iterable as you specify above.</p> <pre><code>Iterable&lt;Iterable&lt;S&lt;Double&gt;&gt;&gt; doubleIterables = Iterables.map(numbers, castOrNull(Double.class)); </code></pre> <p>We can then concatenate all these together to produce one iterable again, which has all of the desired values and none of those we want to remove.</p> <pre><code>Iterable&lt;S&lt;Double&gt;&gt; doubles = Iterables.concat(doubleIterables); </code></pre> <p><em>Disclaimer: I haven't tried compiling this. You may have to play around with generics to get it to work.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload