Passing Lambda Expressions to Methods - Java Lambda Stream

Java examples for Lambda Stream:Lambda

Description

Passing Lambda Expressions to Methods

Demo Code

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class Main {
  public static Double calculate(Function<List<Double>, Double> f1,
      Double[] args) {/*from w  ww .  j a  va 2  s  .co  m*/
    Double returnVal;
    List<Double> varList = new ArrayList();
    int idx = 0;
    while (idx < args.length) {
      varList.add(args[idx]);
      idx++;
    }
    returnVal = f1.apply(varList);
    return returnVal;
  }

  public static void main(String[] args) {

    double x = 16.0;
    double y = 30.0;
    double z = 4.0;

    // Create volume calculation function using a lambda
    Function<List<Double>, Double> volumeCalc = list -> {
      if (list.size() == 3) {
        return list.get(0) * list.get(1) * list.get(2);
      } else {
        return Double.valueOf("-1");
      }
    };
    Double[] argList = new Double[3];
    argList[0] = x;
    argList[1] = y;
    argList[2] = z;

    // Create area calculation function using a lambda. This particular
    // calculator ignores a third argument in the list, if it exists.
    Function<List<Double>, Double> areaCalc = list -> {
      if (list.size() == 2) {
        return list.get(0) * list.get(1);
      } else {
        return Double.valueOf("-1");
      }
    };
    Double[] argList2 = new Double[] { x, y };

    System.out.println("The volume is: " + calculate(volumeCalc, argList));
    System.out.println("The area is: " + calculate(areaCalc, argList2));
  }
}

Result


Related Tutorials