Define
functional interface that takes one value and return other.
ProcessorFunction.java
package com.sample.functional.interfaces; /** * Functional interface that takes one value and return other value. * * @author krishna * * @param <T> * Input value type * @param <U> * Output value type */ public interface ProcessorFunction<T, U> { public U process(T obj); }
Application.java
package com.sample.app; import java.util.ArrayList; import java.util.List; import com.sample.functional.interfaces.ProcessorFunction; public class Application { public static int getNoOfMatchedEle(ProcessorFunction<List<Integer>, Integer> processorFun, List<Integer> list) { return processorFun.process(list); } public static void main(String[] args) { List<Integer> input = new ArrayList<>(); input.add(1); input.add(10); input.add(21); input.add(11); input.add(31); /* Get total elements */ int totalEle = getNoOfMatchedEle((list) -> { return list.size(); }, input); int eleGreater20 = getNoOfMatchedEle((list) -> { int count = 0; for (int i : list) { if (i > 20) count++; } return count; }, input); String result1 = String.format("Total elements in the list are %d", totalEle); String result2 = String.format("Elements > 20 are %d", eleGreater20); System.out.println(result1); System.out.println(result2); } }
Output
Total elements in the list are 5 Elements > 20 are 2
No comments:
Post a Comment