In the following code sample what does the ::
do:
public static void main(String[] args) {
List<Integer> l = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer s = l.stream().filter(Tests::isGT1)
.filter(Tests::isEven)
.map(Tests::doubleIt)
.findFirst()
.orElse(100);
System.out.println(s);
}
private static boolean isGT3(int number){
return number > 3;
}
private static boolean isEven(int number){
return number % 2 ==0;
}
private static int doubleIt(int number){
return number * 2;
}
The double colon (::) operator, also known as method reference operator in Java, is used to call a method by referring to it with the help of its class directly. They behave exactly as the lambda expressions.
In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).
The operator's precedence refers to the order in which operators are evaluated within an expression whereas associativity refers to the order in which the consecutive operators within the same group are carried out. Precedence rules specify the priority (which operators will be evaluated first) of operators.
These are method references. It's just a simpler way to write a lambda expression:
.map(Tests::doubleIt)
is equivalent to
.map(i -> Tests.doubleIt(i))
You can also refer to instance methods using someObject::someMethod
, or even to constructors using SomeClass::new
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With