Monday, 17 July 2017

What does :: Java operator do in this context?





In the following code sample what does the :: do:



public static void main(String[] args) {

List 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;
}


Answer



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.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...