I wanted to understand :: operator a bit more, and with this intention, created a sample program:
public class Second {
public static void main(String[] args) {
doWork(new int[] { 1, -1, 2, -1, 0, 2, 0, 0 });
}
public static void doWork(int[] nums) {
// This is a compilation error - how do
// we create an object and invoke method?
Arrays.stream(nums).forEach((Myclass1::new)::print);
}
@FunctionalInterface
interface MyInterf1 {
public abstract void print(int i);
}
public class Myclass1 implements MyInterf1 {
private int i;
public Myclass1(int i) {
this.i = i;
}
@Override
public void print(int i) {
System.out.println(this.i);
}
}
}
My intent is simple:
To print each element, using "::" to invoke the print() method of Myclass1. As this method is non-static, so I need to first create the object of this class and then invoke.
Is it possible at all? How do we simplify both object creation (using::) and then invoking method on that object?