Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does :: Java operator do in this context? [duplicate]

Tags:

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;
}
like image 537
a_z Avatar asked Jun 07 '15 13:06

a_z


People also ask

What is the :: operator in Java?

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.

What does the question mark do in Java?

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).

What is operator precedence and associativity in Java?

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.


1 Answers

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.

like image 154
JB Nizet Avatar answered Jan 03 '23 18:01

JB Nizet