1. Lambda: A lambda expression can implement a functional interface by defining an anonymous function that can be passed as an argument to some method.
2. Functional Interface :
A functional interface is an interface that contains only one abstract method.
They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods.
Pre-define functional Interface In JAVA
· Consumer
· Supplier
· Predicate
· Function
We can create own functional interface .
Ex.
@FunctionalInterface
public interface MyOwnFunctionalInterface {
displayMesaage(String msg);
}
3. Stream API: The Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
Q1) Why, how and where we use these features?
A) Why Java need Lambda ?
1. Enables functional programming:
1.1) What is functional programming ?
Functional programming is a programming paradigm in which we try to bind everything in pure mathematical functions style. It is a declarative type of programming style. Its main focus is on “what to solve” in contrast to an imperative style where the main focus is “how to solve”. It uses expressions instead of statements. An expression is evaluated to produce a value whereas a statement is executed to assign variables.
Programming Languages that support functional programming: JavaScript, Python
Example
sum (a, b) // sum is function taking x and y as arguments
return a + b // sum is returning sum of x and y without changing them
B) Why Functional interface in Java8?
A functional interface is an interface that contains only a single abstract method (a method that doesn't have a body).
The main reason why we need functional interfaces is that we can use them in a lambda expression and method references.
This way we reduce boilerplate code (In computer programming, boilerplate code are the sections of the code that have to be included in many places without or with, little alterations).
C) Why Stream API in Java8?
There are a lot of benefits to using streams in Java, such as the ability to write functions at a more abstract level which can reduce code bugs, compact functions into fewer and more readable lines of code, and the ease they offer for parallelization.
Comments