Functional Programming with Java Tutorial
Selected Reading
- Discussion
- Resources
- Quick Guide
- Fixed Length Streams
- Infinite Streams
- Terminal methods
- Intermediate Methods
- Exception Handling
- Type Inference
- Pure Functions
- First Class Functions
- Returning a Function
- High Order Functions
- Collections
- Constructor References
- Method References
- Functional Interfaces
- Default Methods
- Lambda Expressions
- Reducing
- Currying
- Closure
- Optionals & Monads
- Parallelism
- Recursion
- Persistent Data Structure
- Eager vs Lazy Evaluation
- Functional Composition
- Functions
- Overview
- Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Eager vs Lazy Evaluation
Eager vs Lazy Evaluation
Eager evaluation means expression is evaluated as soon as it is encountered where as lazy evaluation refers to evaluation of an expression when needed. See the following example to under the concept.
import java.util.function.Suppper; pubpc class FunctionTester { pubpc static void main(String[] args) { String queryString = "password=test"; System.out.println(checkInEagerWay(hasName(queryString) , hasPassword(queryString))); System.out.println(checkInLazyWay(() -> hasName(queryString) , () -> hasPassword(queryString))); } private static boolean hasName(String queryString){ System.out.println("Checking name: "); return queryString.contains("name"); } private static boolean hasPassword(String queryString){ System.out.println("Checking password: "); return queryString.contains("password"); } private static String checkInEagerWay(boolean result1, boolean result2){ return (result1 && result2) ? "all conditions passed": "failed."; } private static String checkInLazyWay(Suppper<Boolean> result1, Suppper<Boolean> result2){ return (result1.get() && result2.get()) ? "all conditions passed": "failed."; } }
Output
Checking name: Checking password: failed. Checking name: failed.
Here checkInEagerWay() function first evaluated the parameters then executes its statement. Whereas checkInLazyWay() executes its statement and evaluates the parameter on need basis. As && is a short-circuit operator, checkInLazyWay only evaluated first parameter which comes as false and does not evaluate the second parameter at all.
Advertisements