Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 11 Local-Variable Type Inference Improvement Usage

I am trying to make a use case for the Java 11 extension on var keyword for lambda expressions. The examples I could find online are always related to @NonNull annotation. However when I want to do something like this:

long count = Stream.of(-3, -2, -1, 0, 1, 2, 3, 4)
            .filter((@NegativeOrZero var a) ->  a > -3)
            .count();

System.out.println(count);

I get:

7

I expect to count only -2, -1 and 0 and not count others, or throw an error or something. Same goes for the following:

long count = Stream.of(1, 2, 3, 4, 5, null, 7, 8, 9)
            .filter((@NotNull(message="It is a null!!") var a) ->  a > 5)
            .count();

 System.out.println(count);

I get an NPE without any custom message unless I change a > 5 to a != null && a > 5 which is not related to annotation.

Can someone explain what am I missing here?

Edit: Maybe I forgot to mention but can you provide an example with var keyword and validations combined to understand its benefits?

Edit 2: I found a more simple example that is supposed to throw an error. However, for me, it returns true. I am using JDK 13 btw.

Predicate<String> predicate = (@NotNull var a) -> true;
System.out.println(predicate.test(null));
like image 912
Okan Menevşeoğlu Avatar asked Jul 12 '26 02:07

Okan Menevşeoğlu


1 Answers

java.util.stream classes are not in any way related to javax.validation so the stream won't understand or process @NotNull or @NegativeOrZero. When you annotate type you only provide the metadata. Something has to process this metadata to create the desired behavior, and stream does not.

Your examples are evaluated as:

Stream.of(-3, -2, -1, 0, 1, 2, 3, 4)
      .filter((var a) -> a > -3)
      .count(); // 7 as only -3 is filtered out
Stream.of(1, 2, 3, 4, 5, null, 7, 8, 9)
      .filter((var a) -> a > 5) // NPE on boxing null
      .count(); 
like image 60
Karol Dowbecki Avatar answered Jul 14 '26 16:07

Karol Dowbecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!