Java Lambda Expression Passing Lambda Expressions as Arguments

Introduction

Passing a lambda expression as an argument is a common use of lambdas.

To receive a lambda expression as an argument, the parameter type receiving the lambda expression must be a functional interface type compatible with the lambda.


// Use lambda expressions as an argument to a method. 

interface StringFunc {
  String func(String n);//from   w w  w. jav  a 2 s  . c o  m
}

public class Main {

  static String stringOp(StringFunc sf, String s) {
    return sf.func(s);
  }

  public static void main(String args[]) {
    String inStr = "this is a test from demo2s.com";
    String outStr;

    System.out.println("Here is input string: " + inStr);

    outStr = stringOp((str) -> str.toUpperCase(), inStr);
    System.out.println("The string in uppercase: " + outStr);

    outStr = stringOp((str) -> {
      String result = "";
      int i;

      for (i = 0; i < str.length(); i++)
        if (str.charAt(i) != ' ')
          result += str.charAt(i);

      return result;
    }, inStr);

    System.out.println("The string with spaces removed: " + outStr);

    StringFunc reverse = (str) -> {
      String result = "";
      int i;

      for (i = str.length() - 1; i >= 0; i--)
        result += str.charAt(i);

      return result;
    };

    System.out.println("The string reversed: " + stringOp(reverse, inStr));
  }
}

The following code creates a BiFunction object and pass to a method.


import java.util.function.BiFunction;

public class Main {
  public static void main(String[] args) {
    BiFunction<String, String, Integer> function = (s, s1) -> (s + s1).length();

    doOperation(function, "demo from ", "demo2s.com");
  }//from w  w w.j ava 2 s  .co m

  public static void doOperation(BiFunction<String, String, Integer> function, String str, String str1) {
    int value = function.apply(str, str1);
    System.out.println(":" + value);
  }

}

The following code creates a BiConsumer object and pass to a method.

import java.util.function.BiConsumer;

public class Main {
  public static void main(String[] args) {
    print((a,b) -> System.out.println(a+" "+b), "Hello","Java");
    print((a,b) -> System.out.println(a+"-"+b), "Hello","Java");
  }/*from w ww  . j  a  v a 2s  .co  m*/

  public static void print(BiConsumer<String, String> biConsumer, String str, String str1) {


    biConsumer.accept(str, str1);
  }
}



PreviousNext

Related