On Mon, 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); > I second this suggestion. I have thought about suggesting this for a long time as well. As it really bothers me missing that method. I have been using a pre 8.0 stream-like library and in many situations this method has really saved some ugly boiler plating code. The other default function I would like to see is stream.toList() (I can live with collectToList) which is short for s.collect(Collectors.toList()). 50 % of my terminal functions are s.collect(Collectors.toList()). And I took a look at libraries that uses the Stream interface GitHub and it is roughly the same usage. - Kasper