You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Stream#filter with a null-rejecting lambda is not treated like filter(Objects::nonNull) when inferring a collector's type variable #2127
With JSpecifyExperimental, stream.filter(Objects::nonNull) refines the element type to non-null, but stream.filter(s -> s != null) does not do so for a downstream collector: the inference failure below is reported, although the code is null-safe. (This may be better categorized as a feature request than a bug.)
Repro4.java:16: warning: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable
.collect(Collectors.groupingBy(String::trim));
^
Reproduced with NullAway 0.14.3 and with master (002c08d), Error Prone 2.51.0, JDK 25. No diagnostic is reported with -XepOpt:NullAway:WarnOnGenericInferenceFailure=false.
Observations:
With .filter(Objects::nonNull) there is no diagnostic.
.filter(s -> s != null).map(s -> s.trim()) is accepted, but .filter(s -> s != null).map(String::trim) yields the regular "unbound instance method reference cannot be used, as first parameter of functional interface method Function.apply(@Nullable String) is @Nullable" error. So lambda-form filters are refined for lambdas, but not for method references or collectors.
s -> s != null && s.isEmpty() behaves the same, and cannot be rewritten using Objects::nonNull. Real-world example: .filter(s -> s != null && s.isEnum()).collect(collectingAndThen(toImmutableSetMultimap(Symbol::asType, Symbol::toString), ...)) (1 of 15 failures in our code base).
I'd like to look into this. Since you note it may be a feature request: should a null-rejecting lambda in Stream#filter, such as s -> s != null, refine the element type the way filter(Objects::nonNull) does? If that is wanted, I can start there and include the s != null && ... case. I have not reproduced it myself yet.
I'm not a maintainer on this project, but yes I'd expect .filter(Objects::nonNull) and .filter(s -> s != null) to have identical impact on the nullness of the resultant stream.
Activity
adityaanikam commentedon Dec 3, 2026
I'd like to look into this. Since you note it may be a feature request: should a null-rejecting lambda in
Stream#filter, such ass -> s != null, refine the element type the wayfilter(Objects::nonNull)does? If that is wanted, I can start there and include thes != null && ...case. I have not reproduced it myself yet.Stephan202 commentedon Dec 3, 2026
I'm not a maintainer on this project, but yes I'd expect
.filter(Objects::nonNull)and.filter(s -> s != null)to have identical impact on the nullness of the resultant stream.Edit: and, thanks for looking into this!