Reputation: 11739
I don't understand why raw type Predicate
causes compilation error even if I have a type cast. Let's look at the following example:
From a list containing different objects get the ones which extend Number
, cast to a Number
and collect to a List
.
List<Object> objectList = Arrays.asList(1, 3.4, 2, new Object(), "");
List<Number> numbers = objectList
.stream()
.filter(Number.class::isInstance)
.map(Number.class::cast)
.collect(Collectors.toList());
Let's do the same thing, but this time let's cast Number.class::isInstance
to Predicate
:
List<Number> numbers1 = objectList.stream()
.filter((Predicate) Number.class::isInstance)
.map(Number.class::cast)
.collect(Collectors.toList());
This leads to a compilation error:
Error:(28, 25) java: incompatible types: java.lang.Object cannot be converted to java.util.List
There is a cast after a filter
operation .map(Number.class::cast)
and .collect(Collectors.toList());
But the final type is java.lang.Object
. Why do you think the result type is java.lang.Object
and not a List<Number>
?
Upvotes: 4
Views: 262
Reputation: 272517
filter
, it returns a raw Stream
.map
would be <R> Stream<R> Stream<T>::map(Function<? super T, ?
super R> function)
. But now there is no T
, so the argument is forced to be a raw Function
type, so map
too ends up returning a raw Stream
.collect
returns an Object
.Upvotes: 3