Sunday 13 May 2018

Lambda expression that computes a value based on multiple inputs

Define a functional interface, that computes a value based on multiple values.

ProcessorFunction.java
package com.sample.functional.interfaces;

/**
 * Functional interface that takes multiple values as input and return other value as result.
 * 
 * @author krishna
 *
 * @param <T>
 * @param <U>
 * @param <V>
 * @param <W>
 */
public interface ProcessorFunction<T, U, V, W> {

 public W process(T obj1, U obj2, V obj3);
}

Application.java
package com.sample.app;

import java.util.*;
import java.util.List;

import com.sample.functional.interfaces.ProcessorFunction;

public class Application {

 public static int getNoOfMatchedEle(
   ProcessorFunction<List<Integer>, Set<Integer>, Map<Integer, Integer>, Integer> processorFun,
   List<Integer> list, Set<Integer> set, Map<Integer, Integer> map) {

  return processorFun.process(list, set, map);

 }

 public static void main(String[] args) {
  List<Integer> list = new ArrayList<>();
  list.add(1);
  list.add(21);
  list.add(11);
  list.add(13);
  list.add(31);

  Set<Integer> set = new HashSet<>(list);

  Map<Integer, Integer> map = new HashMap<>();
  map.put(100, 199);
  map.put(5, 11);
  map.put(15, 47);
  map.put(2, 3);

  int totalEle = getNoOfMatchedEle((myList, mySet, myMap) -> {
   int totalElements = myList.size() + mySet.size() + myMap.size();
   return totalElements;
  }, list, set, map);

  int eleGreater20 = getNoOfMatchedEle((myList, mySet, myMap) -> {
   int totalElements = 0;

   for (int ele : myList) {
    if (ele > 20)
     totalElements++;
   }

   for (int ele : mySet) {
    if (ele > 20)
     totalElements++;
   }

   for (int ele : myMap.keySet()) {
    if (ele > 20)
     totalElements++;
   }
   return totalElements;
  }, list, set, map);

  String result1 = String.format("Total elements are : %d", totalEle);
  String result2 = String.format("Total elements > 20 are : %d", eleGreater20);

  System.out.println(result1);
  System.out.println(result2);
 }
}


Output

Total elements are : 14
Total elements > 20 are : 5




Previous                                                 Next                                                 Home

No comments:

Post a Comment