Using Predefined Interfaces for Lambda in Java

There are convenient predefined Interfaces in Java for writing functions in Lambda Expression.  By using those Interfaces, we don't need to write our own (in many cases) and that can help simplifying code.

Those Interfaces are defined in java.util.function package that has been available since Java 8.  Import that package before using the Interfaces.

import java.util.function.*;
import java.util.Arrays;

class PredefInterface4LambdaDemo {    
    
    public static void main (String args[]) {
        
        Integer[] numHousesSold = {5, 4, 5, 6, 8, 9, 9, 10, 9, 9, 6, 5};                        
        Arrays.sort (numHousesSold);
        
        System.out.println ("For the number of houses sold in the last 12 months: ") ;
        
        // This function applies an operation to an obejct of Integer[], and
        // return the result as an object of Double.
        Function<Integer[], Double> mean = (array) -> {            
            double sum = 0d;
            for (int num: array) sum += num;
            return sum / array.length;
        };
        System.out.println ("Mean = " + mean.apply(numHousesSold));

        // This function applies an operation to an obejct of Integer[], and
        // return the result as an object of Integer.
        Function <Integer[], Integer> findMin = (array) -> {
            return numHousesSold[0];
        };    
        System.out.println ("Lowest volume = " + findMin.apply(numHousesSold));

        // This function applies an operation to an object of Integer[], and
        // return the result as an object of the same.
        UnaryOperator <Integer[]> findTop3 = (array) -> {
            Integer[] top3 = new Integer[3];
            for (int i=1; i<4; i++)
                top3[i-1] = numHousesSold[array.length-i];
            return top3;
        };        
        Integer[] top3 = findTop3.apply(numHousesSold);
        System.out.println ("Top 3 volume = " + Arrays.toString(top3));
    }
}

The above program produces this result:

For the number of houses sold in the last 12 months:
Mean = 7.083333333333333
Lowest volume = 4
Top 3 volume = [10, 9, 9]

The program demonstrates the use of two predefined Interfaces: Function <T, R>, and UnaryOperator <T>.  There are more predefined Interfaces in the java.util.function package. Find out more from the official Java documentation.

Comments

Popular posts from this blog

Finding Median by Stream

Factorial by Different Styles in Java

Reduction by Java Stream