Scala's collection provides a method called collect that merges filter and map into a single method. It's particularly useful when filtering an Object collection to produce a subset of that collection containing only a particular type.
Is there any such thing with Java 8's Stream?
解决方案
Having a combination of filter and map in one step is not that useful in Java given its type system. E.g. there is no such PartialFunction type.
The closest thing is flatMap:
List list=Arrays.asList(0, "foo", 0L, 42.0, true, "false");
List sList = list.stream()
.flatMap(o-> o instanceof String? Stream.of((String)o): Stream.empty())
.collect(Collectors.toList());
System.out.println(sList);
but the expressiveness of
.flatMap(o-> o instanceof String? Stream.of((String)o): Stream.empty())
is not that bigger compared to
.filter(o -> o instanceof String).map(o -> (String)o)
Of course, you may create a helper method encapsulating these steps in a single, undissolvable operation:
static Stream onlyType(Stream> s, Class type) {
return s.filter(type::isInstance).map(type::cast);
}
then you can use it like
List sList=onlyType(list.stream(), String.class).collect(Collectors.toList());