Monday, 24 May 2021

Lambda Expression in Java 8

Lambda Expression













Lambda calculus was the big change in Mathematical world which came in 1930s.
Because of this programmers also started using it.

LISP is the 1st lang where lambda expressions came first.
Apart form LISP, C, CPP, PYTHON, SCALA, RUBBY, Objective C

Advantages

  1. To enable functional programming in java
  2. To write more readable, maintainable and concise code
  3. To use APIs very easily and effectively.
  4. To enable parallel processing
Lambda Expressionlambda expressions are a means to create anonymous classes of functional interfaces easily
     1. No Name
     2. No Return Type
     3. No Access Modifier

NOTE : Only use in case of functional interface.


Functional Interface : An interface having only one abstract method is known as Functional Interface.
Example : Runnable , Callable etc.

There are some rules to write lambda expression from which two main important rules are
1. If body is having only one statement then { } braces are optional
2. If passing parameter as an argument then argument type is optional

Example.

public void display(String str){
    System.out.println("Hello "+str);
}
Using lambda
(str)->System.out.println("Hello "+str);
or
str->System.out.println("Hello "+str);
int getValue(){
  return 5;
}
Using lambda
() -> 5
// concatenating two strings, it has 2 string parameters and they are concatenated in lambda body
(String s1, String s2) -> s1+s2;


Below are some example codes using lambda

1. Calculator program
























2. Threading



Scenarios

  1. (int x, int y) -> x+y; or (x, y) -> x + y; which one of these is a valid lambda expression?

    Both of them are valid lambda expressions if used in a correct context.


  2. (int x, y) -> x + y; is this a valid lambda expression?

    You can't have lambda expression where type for only one of the parameter is explicitly declared so this lambda expression is invalid.

Read More »

Monday, 17 May 2021

10.0 Collection Framework in Java

Collection Framework

Why there is need of collection framework ?

 Limitation of Array : 

1. Fixed in Size - If we give less size then we can't expand it at run time, If we give more space then unused space will be of no use.

2. They are Homogeneous in type, we can only store similar type of data into an Array.

3. There is underlying data structure behind this as a result of there is no additional supporting methods are available.

Collections are grow able in nature.

Note : Arrays are highly recommended  because of its high performance but memory wise collections are good.


What is Collection ?

Group of individual object as a  single entity.

Java provides several classes and interfaces to achieve this also know as Collection Framework.


There are 9 key Interface




Read More »