What is a method reference
It is basically a pointer to a function
class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
} } Counter counter = new Counter(); Runnable action = counter::increment; action.run(); action.run(); System.out.println(counter.getCount()); // 2 Here counter::increment is a pointer to the function When action.run() is called - increment() is called on the specific counter object. It doesn’t copy the object — it calls the real method and mutates that same instance.Type 1 : Static Method
ClassName::staticMethod
Type 2: Instance method of a particular object
Instance method of a particular object
instance::methodName
Calls a method on a specific object - That means if I use this in a stream operation method belonging to SAME object will be called again and again
ClassName::instanceMethod
Calls a method on each element. That means if I use this in a stream operation method belonging to DIFFERENT object from the stream will be called. So you stream should be of type ClassName so that you are calling the methods on a unique object each time
ClassName::new
Creates a new object
Equivalent to () -> new ClassName()
State Mutation
Since the method reference has access to private variables of the Object, you can technically modify the value of the variables, but this is not recommended, unless you have a strong reason for doing so
Lambda
Easier to think of it as a pointer to a function
(x, y) -> x + y
(parameters) -> { statements }
Can i refer a variable from outside the lambda’s scope in the lambda
Only if they are Final or effectively final local variables
int base = 10;
Function<Integer, Integer> adder = x -> x + base;
System.out.println(adder.apply(5));
“Effectively Final” - You can use an outside variable inside a lambda only if it is not modified after it’s defined.