Sunday 13 May 2018

Lambda Expression that accepts two objects and return a result

Define a Functional interface that accepts two objects (Objects can be of same type (or) different type) and return a result.

BiObjectFunction.java

package com.sample.functional.interfaces;

/**
 * Functional interface that accepts two object and compute the result by
 * processing these two objects.
 * 
 * @author Krishna
 *
 * @param <T1>
 *            First value type
 * 
 * @param <T2>
 *            Second value type
 * @param <R>
 *            Third value type
 */
public interface BiObjectFunction<T1, T2, R> {

 /**
  * Calculate the value by processing two input arguments.
  * 
  * @param object1
  *            First value
  * @param object2
  *            Second value
  * @return result by processing <code>object1</code>, <code>object2</code>
  */
 public R processInfo(T1 object1, T2 object2);
}

Application.java

package com.sample.app;

import com.sample.functional.interfaces.BiObjectFunction;

public class Application {

 private static Integer processInfo(BiObjectFunction<Integer, Integer, Integer> bijFunc, Integer value1,
   Integer value2) {
  return bijFunc.processInfo(value1, value2);
 }

 public static void main(String args[]) throws Exception {
  int val1 = 20;
  int val2 = 10;

  int sum = processInfo((a, b) -> {
   return a + b;
  }, val1, val2);

  int sub = processInfo((a, b) -> {
   return a - b;
  }, val1, val2);

  int multiplication = processInfo((a, b) -> {
   return a * b;
  }, val1, val2);

  String res1 = String.format("Sum of %d and %d is %d", val1, val2, sum);
  String res2 = String.format("Sub of %d and %d is %d", val1, val2, sub);
  String res3 = String.format("Multiplication of %d and %d is %d", val1, val2, multiplication);

  System.out.println(res1);
  System.out.println(res2);
  System.out.println(res3);
 }
}


Output

Sum of 20 and 10 is 30
Sub of 20 and 10 is 10
Multiplication of 20 and 10 is 200



Previous                                                 Next                                                 Home

No comments:

Post a Comment