D2 - Java's version of lambdas & Streams

Software, Java

Java's version of lambdas

Today i've learned about how lambdas work in Java. It's not as straight-forward as in python. In java, it's actually an implicit implementation of an existing interface, so for one to be able to write a lambda expression, he must first create an interface with a single desired function's signature.

Small example:

public class SomeClass{
    public interface InterName {
        public static int funcName(int x);
    }

    public static int[] numManipulation(InterName m) {  
        int[] intArray = {0, 1, 5, 10};  
        for (int num : intArray) {                  
            System.out.println(m.funcName(num));    
        }
    }

    public static void main(String[] args) {  // A regular main function.
        numManipulation(z -> z*18);     // Lambda expression
    } 
}

Output:

0
18
90
180

So, in short: An interface called InterName is made, with a function (funcName) that recieves an integer and returns an integer. The next function (numManipulation) recieves an instance of the interface above, as an argument. Within numManipulation we print each number within our array after it has been manipulated by m.funcName, the interface function above (which we didn't provide any implementation for, yet).

Now comes the lambda expression: in our main function we call numManipulation which recieves, as we said, an instance of InterfaceName as an argument. But as an argument, we write our lambda expression, which is the implementation for funcName within InterfaceName. In this case, funcName takes an integer, multiply it by 18, and return the result.

While our lambda expression itself seems quite straightforward, to understand why it works we must explain how java understands it.

so java actually read the lambda expression (z->z*18) as a full implementation of funcName, which equals:

public static int funcName(int x) {return x*18;}

Since the interface has only 1 abstract function, and it is passed down as an argument within numManipulation's signature, the lambda expression is recognized as an implementation of the only function said interface has.

Java streams

Streams in java don't provide any new building/creation possibilities. Their only role (which is pretty big) is reducing the amount of code necessary for certain actions. Instead of writing a loop full of conditions, we can write a few lines with lambda expressions that are quite intuitive to understand.

int[] ints = {1, 2, 3, 4};
ints.stream()
      .filter(x->x%2==0)
      .forEach(System.out::println);

The short code above takes the ints array and prints only the even numbers. It might seem unnecessary at first glance, but in bigger cases (more filtering/manipulation required) it turns out to be much more compact than a regular loop/iteration.

RwK