Obviously, this is yet another possible workaround. But it is a
workaround. There really aren't that many rough edges with the set of
methods added with lambdas, but this is definitely one. That Guava
handled it specially is another good indication.

BTW, I wait months before making this request to see if it really was
common enough a pattern, but I'm confident that it is now.

Stephen


On 27 April 2015 at 14:41, Paul Sandoz <paul.san...@oracle.com> wrote:
> Hi Stephen,
>
> You can do this:
>
> static <T> Function<Object, Stream<T>> casting(Class<T> c) { // bike shed for 
> clearer name
>     return o -> Stream.ofNullable(c.isInstance(o) ? c.cast(o) : null);
> }
>
>
> Object[] s = Stream.of(1, 2, "3", 4).toArray();
> Stream.of(s).flatMap(casting(Integer.class)).
>         forEach(System.out::println);
>
>
> I am a bit reluctant to add such a specific kind of filter method to Stream 
> when one can do the above.
>
> In general my preference is to keep the stream operation methods as general 
> as possible.
>
> Paul.
>
> On Apr 27, 2015, at 3:22 PM, Stephen Colebourne <scolebou...@joda.org> wrote:
>
>> This is a request for an additional method on java.util.stream.Stream.
>>
>> Having written quite a bit of code in Java 8 now, one annoyance keeps
>> on coming up, filtering and casting the stream.
>>
>> Currently, it is necessary to do this:
>>
>>    return input.stream()
>>        .filter(Foo.class::isInstance)
>>        .map(Foo.class::cast)
>>        .someTerminalOperation();
>>
>> or
>>
>>    return input.stream()
>>        .filter(t -> t instanceof Foo)
>>        .map(t -> (Foo) t)
>>        .someTerminalOperation();
>>
>> Really, what is needed is this:
>>
>>    return input.stream()
>>        .filter(Foo.class)
>>        .someTerminalOperation();
>>
>> For info, Guava's FluentIterable has such a method.
>>
>> The new method signature would be something like:
>>
>> public Stream<R> filter(Class<R> cls);
>>
>> As far as I can see, there is no problem in implementing this in both
>> serial and parallel modes, as it is essentially just a convenience.
>>
>> Thoughts?
>> Stephen
>

Reply via email to