React Cheatsheet

This is a cheat sheet to React for daily use. It contain a lot of snippets from my own use.

Table of Contents

  1. React
  2. Redux

1 – React

Use React

// Import React and ReactDOM
import React from 'react'
import ReactDOM from 'react-dom'
// Render JSX into a DOM element
ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);
// Render Component into a DOM element
ReactDOM.render(
  <MyComponent />,
  document.getElementById('root')
);

JSX

// JSX produce React Element
const item = <h1>My JSX Element</h1>;
// Use curly braces to embed some Javascript
const item = <div>{getContent()}</div>;
// Use camelCase for attribute name
const item = <div className="example"></div>;
// Use curly braces to embed some Javascript
const item = <img src={image.url}></img>;
// Self close if tag is empty
const item = <div />;

Components

// Stateless Functional Component
function Heading(props) {
  return <h1>{props.title}</h1>;
}
// Stateless Functional Component (with arrow function)
const Heading = (props) => {
  return <h1>{props.title}</h1>;
}
// ES6 Class Component, can have states
class Heading extends React.Component {
  render() {
    return <h1>{this.props.title}</h1>;
  }
}
// Always start component names with capital
<Heading />

Render

// Return React Element
render() {
  return <div>Example of return<div />
}
// Return Another Component
render() {
  return <MyComponent />
}
// Return String
render() {
  return 'Return a string works!'
}
// Return Numbers (rendered as text node)
render() {
  return 100
}
// Return nothing
render() {
  return null
}

Component Lifecycle

componentWillMount() {

}
componentDidMount() {
  // Call after the component output has been rendered in the DOM
}
componentWillReceiveProps() {

}
shouldComponentUpdate() {

}
componentWillUpdate() {

}
componentDidUpdate() {

}
componentWillUnmount() {

}
componentDidCatch() {

}

Props (Properties)

Props are immutable.

// Component with a single valid argument : props
function Heading(props) {
  return <h1>{props.title}</h1>;
}

State

State are locals and fully controlled by the component itself.

// Update state with setState, except in constructor
this.setState({
  title: 'Updated title',
});
// Set state with previous state
this.setState((prevState, props) => {
  return {count: prevState.count + 1};
});
// Declare initial state in constructor
class Heading extends React.Component {
  constructor(props) {
    super(props);
    this.state = {title: 'My title'};
  }
}
// Do not update state directly
this.state.title = 'Hello';
// Lifting state up to share state between component
class Wrapper extends React.Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.state = {value: ''};
  }

  handleInputChange(value) {
    this.setState({value});
  }
  render() {
    const value = this.state.value;
    return (
        <Input value={value} onInputChange={this.handleInputChange} />
    );
  }
}

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onInputChange(e.target.value);
  }

  render() {
    const value = this.props.value;
    return <input value={value} onChange={this.handleChange} />;
  }
}

Handling Event

// React Event are in camelCase
<button onClick={handleClick}>
  Action
</button>
// Use preventDefault instead of return false
function handleClick(e) {
  e.preventDefault();
}
// Bind this to use it in the callback
constructor(props) {
  super(props);
  this.handleClick = this.handleClick.bind(this);
}
// Pass data to callback
<button onClick={(e) => this.deleteItem(id, e)}>Delete item</button>
<button onClick={this.deleteItem.bind(this, id)}>Delete item</button>

Conditional Rendering

// Using if operator with props
function Heading(props) {
  const isHome = props.isHome;
  if (isHome) {
    return <HomeHeading />;
  }
  return <PageHeading />;
}
// Using if operator with state
render() {
  const isHome = this.state.isHome;
  let heading = null;
  if (isHome) {
    heading = <HomeHeading />;
  } else {
    heading = <PageHeading />;
  }

  return (
    <div>
      {heading}
    </div>
  );
}
// Using ternary operator
<div>
  {isHome ? <HomeHeading /> : <PageHeading />}
</div>
// Using logical operator
<div>
  {messages.length > 0 &&
    <h1>
      You have messages
    </h1>
  }
</div>
// Prevent component from rendering
function Modal(props) {
  if (!props.isShow) {
    return null;
  }

  return (
    <div>
      Modal
    </div>
  );
}

Portal

import { createPortal } from "react-dom";

class MyPortalComponent extends React.Component {
  render() {
    return createPortal(
      this.props.children,
      document.getElementById("node"),
    );
  }
}

Fragment

const Fragment = React.Fragment;

render() {
  return (
    <Fragment>
      Some text.
      <h2>A heading</h2>
      Even more text.
    </Fragment>
  );
}
render() {
  return (
    <React.Fragment>
      Some text.
      <h2>A heading</h2>
      Even more text.
    <React.Fragment>
  );
}
render() {
  return (
    <>
      <ComponentA />
      <ComponentB />
    </>
  );
}

Forms

Controlled Components

// In controlled component, each state mutation have an handler function
class Form extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({value: e.target.value});
  }

  handleSubmit(e) {
    alert('Submitted value: ' + this.state.value);
    e.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
// Force to uppercase in handler
handleChange(e) {
  this.setState({value: e.target.value.toUpperCase()});
}
//  in React use a value attribute</span>
<span class="pl-k"><</span>textarea value<span class="pl-k">=</span>{<span class="pl-c1">this</span>.<span class="pl-smi">state</span>.<span class="pl-c1">value</span>} onChange<span class="pl-k">=</span>{<span class="pl-c1">this</span>.<span class="pl-smi">handleChange</span>} <span class="pl-k">/</span><span class="pl-k">></span></pre>
</div>
//  use a value and not a selected attribute
select value={this.state.value} onChange={this.handleChange}>
  option value="a">Option A/option>
  option value="b">Option B/option>
/select>
// 
select multiple={true} value={['a', 'b']}>
// Handle multiple inputs with name attribute
handleInputChange(e) {
  const target = e.target;
  const value = target.value;
  const name = target.name;

  this.setState({
    [name]: value
  });
}

render() {
  return (
    form>
      input name="firstName" onChange={this.handleInputChange} />
      input name="lastName" onChange={this.handleInputChange} />
    /form>
  );
}

<h3><a id="user-content-react-without-jsx" class="anchor" href="#react-without-jsx" aria-hidden="true"></a>React without JSX</h3>

// This two elements are similar :
const element = (
  h1 className="heading">
    Hello!
  /h1>
);

const element = React.createElement(
  'h1',
  {className: 'heading'},
  'Hello!'
);

<h3><a id="user-content-typechecking-props-with-proptypes" class="anchor" href="#typechecking-props-with-proptypes" aria-hidden="true"></a>Typechecking props with PropTypes</h3>

// Use PropTypes
import PropTypes from 'prop-types';
// Prop is an optional array
MyComponent.propTypes = {
  optionalArray: PropTypes.array,
};
// Prop is an optional boolean
MyComponent.propTypes = {
  optionalBool: PropTypes.bool,
};
// Prop is an optional function
MyComponent.propTypes = {
  optionalFunc: PropTypes.func,
};
// Prop is an optional number (integer, float...)
MyComponent.propTypes = {
  optionalNumber: PropTypes.number,
};
// Prop is an optional object
MyComponent.propTypes = {
  optionalObject: PropTypes.object,
};
// Prop is an optional string
MyComponent.propTypes = {
  optionalString: PropTypes.string,
};
// Prop is an optional symbol
MyComponent.propTypes = {
  optionalSymbol: PropTypes.symbol,
};
// Prop is an optional node (numbers, strings, elements, array, fragment)
MyComponent.propTypes = {
  optionalNode: PropTypes.node,
};

<h3><a id="user-content-create-react-app" class="anchor" href="#create-react-app" aria-hidden="true"></a>Create React App</h3>

# Create new app
create-react-app my-app

<h3><a id="user-content-fetch-datas" class="anchor" href="#fetch-datas" aria-hidden="true"></a>Fetch datas</h3>

// Use componentDidMount hook with fetch
class PostsList extends Component {
  constructor(props) {
    super(props);
    this.state = {posts: []};
  }

  componentDidMount() {
    fetch('https://example.com/posts')
      .then(response => response.json())
      .then(data => this.setState({ posts: data.posts }));
      .catch(error => console.log(error));
  }
}
// Use Axios library to fetch datas
import axios from 'axios';

componentDidMount() {
  axios.get('/post', {
    params: {ID: 123}
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
}

<h2><a id="user-content-2---redux" class="anchor" href="#2---redux" aria-hidden="true"></a>2 - Redux</h2>
<h3><a id="user-content-install-redux" class="anchor" href="#install-redux" aria-hidden="true"></a>Install Redux</h3>

npm install --save redux
# Install react binding
npm install --save react-redux
# Install dev tools
npm install --save-dev redux-devtools

<h3><a id="user-content-actions" class="anchor" href="#actions" aria-hidden="true"></a>Actions</h3>

// Declare action type
const SUBMIT_FORM = 'SUBMIT_FORM'
// Action shape with payload
{
  type: SUBMIT_FORM,
  payload: {
    firstName: 'John',
    lastName: 'Doe',
  }
}
// Action shape without payload
{
  type: SUBMIT_FORM,
}
// Declare action creator
function submitForm(formData) {
  return {
    type: SUBMIT_FORM,
    payload: {
      firstName: formData.firstName,
      lastName: formData.lastName,
    }
  }
}

<h3><a id="user-content-reducers" class="anchor" href="#reducers" aria-hidden="true"></a>Reducers</h3>

// Declare an initial state
const initialState = {
  firstName: '',
  lastName: '',
  city: '',
}
// Declare a minimal reducer
function userReducer(state = initialState, action) {
  return state;
}
// Handle action in reducer
function userReducer(state = initialState, action) {
  switch (action.type) {
   case SUBMIT_FORM:
     return {
       ...state,
       firstName: action.payload.firstName,
       lastName: action.payload.lastName,
       city: action.payload.city,
     };
   default:
     return state;
 }
}

</article>
</div>
<p>

 

Javascript in better way (ES2016)

Today I’ve some JavaScript techniques for you to make your life easier. In this article I am going to use EcmaScript 2016 or above features which will optimize the code.

String Interpolation

Here is a new way to use strings in JS,  mostly strings being defined in single quotes ( ‘ ) or double quotes ( ” ) but now you can also define with backtick ( ` )

// simple string
const name = `Tony stark`; 

// we can also use variables with string
const score = 25;
const message =`You have scored ${score}`;

Destructing Data

This is one of my favorite technique to get desired data from object/ array

Destructing Object

const user = { name: 'Tony Stark', alias: 'Iron-man' };
// destructing 'name' key from user object
const {name} = user;
console.log(name); // prints : Tony Stark

Destructing Array

const results = [50, 65, 20];
// take 1st element of array as `a` & 3rd element as `b`
const [a, , b] = results;
// it is similar to : const a = results[0]; const b = results[2];

Object Spread

It is a way to add some properties of another object in better way

const cat = { legs : 4, sound : 'meow' } 

// now lets get common properties of cat
const dog = {
...cat,
sound: 'woof'
}

Functions

ES6 introduced many ways to use functions. Here are few ways :

Default parameters

function a(x, y = 2, z = 10) {
    return x * y * z;
}
a(20);      // will return : 400 

Rest Parameters

function fn(x, ...y) {
 return x * y.length;
}
fn(2,'hello',7); // return 4

Playing with array

It is common use case in development when we need to modify array in Javascript. I’m dividing it into four cases – filter, sort, modify & iterate.

Filter

Use filter() method which will return filtered array.

let data = [1, 2, 3, 4, 5]; // an array
 
// fastest way to filter
   data = data.filter(x => x % 2 == 0);

// or
   data = data.filter( (x) => {
            return x % 2 == 0 ? true : false;
         });
// output : [ 2, 4 ]

Sort

// sort array to ascending order
let data = [3, 5, 1, 4, 2]; // an array

    data = data.sort( (x) => {
             return a > b ? 1 : b > a ? -1 : 0;
           });
// output : [1, 2, 3, 4, 5]

Modify Array

To modify array best way is to use map()

// find square or all elements of array  
let data = [ 1, 2, 3, 4, 5];  
data = data.map(x=> x * x)  
// output : [1, 4, 9, 16, 25]

Iterating Array

To iterate array use forEach()

// print elements of array  
let data = [1, 2, 3, 4, 5];  
data = data.forEach(x => console.log(x));

constants

constants are immutable variables which are not going to be re-assigned after the declaration. In such condition it is better to use const instead of  var or let

    // example      const PI = 3.14;      PI > 3    
     // output : true

Internalization Of Angular App

For making your application user-friendly to worldwide audience angular provides internationalization(i18n) tools which will make your app available in multiple languages.

Referenced  from angular official website angular.io and whole blog is described for Angular CLI projects.

Angular i18n features

  • Translating text
  • Displaying dates, numbers, percentages and currencies in local format
  • Handling plural forms

Before practical implementation you need to be familiar with word Locale and Locale ID.

Locale

A locale is an identifier(id) that let sets language accordingly. For Example , If you wants to set french language then needs to set your locale fr .

A Unicode locale identifier is composed of a Unicode language identifier and (optionally) the character -followed by a locale extension. (For historical reasons the character _ is supported as an alternative to -.) For example, in the locale id fr-CA the fr refers to the French language identifier, and the CA refers to the locale extension Canada.

Default Angular Locale : en-US

To set your app’s Locale run following command in console

ng serve --configuration=fr

If using JIT then need to define LOCAL_ID provider in main module ( src/app/app.module.ts )

import { LOCALE_ID, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from '../src/app/app.component';

@NgModule({
 imports: [ BrowserModule ],
 declarations: [ AppComponent ],
 providers: [ { provide: LOCALE_ID, useValue: 'fr' } ],
 bootstrap: [ AppComponent ]
})
export class AppModule { }

For a complete list of locales supported by Angular, see the Angular repository.

i18n Pipes

To format data based on LOCALE_ID angular pipes can help withDatePipeCurrencyPipeDecimalPipe and PercentPipe.

By default, Angular only contains locale data for en-US. If you set the value of LOCALE_ID to another locale, you must import locale data for that new locale. The CLI imports the locale data for you when you use the parameter --configuration with ng serve and ng build.

If you want to import locale data for other languages, you can do it manually:

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

// the second parameter 'fr' is optional
registerLocaleData(localeFr, 'fr');

After this setup we are ready to go with angular i18n translation

Template Translation

Translating text of template in angular very simple just add i18n attribute in  any html tag. For Example :

<h1>Hello Reader</h1>

To translate above add i18n attribute in  <h1> tag

<h1 i18n>Hello Reader</h1>

 

Now we need to generate translation source file by following command

ng xi18n --output-path=locale

For complete reference for generating source files visit Angular’s guide

It will generate default​​​ message.xlf which file in src/locale folder.For french language simply make copy of message.xlf and rename with message.fr.xlf

For above give code i18n attribute will create <trans-unit> tag in .xlf file which will look like

<trans-unit id="ba0cc104d3d69bf669f97b8d96a4559aa3" datatype="html">
 <source>Hello Reader</source>
 ...
 </trans-unit>

<source> tag will contain actual text which i18n attribute read from template. we need to define <target> tag and put translated sentence.

<trans-unit id="ba0cc104d3d69bf669f97b8d96a4559aa3" datatype="html">
 <source>Hello Reader</source>
 <target>Bonjour lecteur</target>
 ...
 </trans-unit>

Now we are all done with i18n configuration. i18n attribute will replace text with <target> value  before angular compilation process starts.

Ways to define i18n attribute

To avoid repeating same words/ sentences in source file we can define i18n attribute with ID which can be defined by @@ prefix. See example below :

<h1 i18n="@@helloReaders">Hello Readers</h1>

For above written code source file will define with id="helloReaders" attribute and for all i18n attribute which contains @@helloReaders Id will be translated by below given <target> value

<trans-unit id="helloReaders" datatype="html">
 <source>Hello Reader</source>
 <target>Bonjour lecteur</target>
 ...
 </trans-unit>

 

To help translator with meaning and description angular provides ability to define it in i18n attribute :

<h1 i18n="site header|An introduction header for this sample">Hello i18n!</h1>

 

In above written code  site header is meaning and rest of | separated sentence is description.

Translating Singular & Plural Forms

Angular i18n tools provides ability to handle pluralization with pretty better way.

Lets understand this with an example : I wants to display notification timing as Just now , One Minute Ago or x minutes ago . To handle this we can write code like this:

<span i18n>Updated 
{minutes, plural, 
 =0 {just now} 
 =1 {one minute ago} other {{{minutes}} minutes ago}}
</span>
  • First parameter is key which contains value actual value.
  • Second parameter will identifies this  as plural translation type.
  • And third parameter define pluralization pattern

Its translation source file will looks like this :

<trans-unit id="5a134dee893586d02bff11056b9cadf9abfad" datatype="html">
 <source>{VAR_PLURAL, plural, =0 {just now} =1 {one minute ago} other {<x id="INTERPOLATION" equiv-text="{{minutes}}"/> minutes ago} }</source>
 <target>{VAR_PLURAL, plural, =0 {à l'instant} =1 {il y a une minute} other {il y a <x id="INTERPOLATION" equiv-text="{{minutes}}"/> minutes} }</target>
 </trans-unit>

 

That’s It for now. I hope you have enjoyed this and will be back soon with more interesting topics like this.

Thanks

 

Stream in Java

Interoduction

Streams bring functional programming to java and are supported starting in java 8

Advantages of streams

  • Make heavy use of lambda expression
  • Parallel streams make it very easy to multi-thread operations
  • Will make you a more efficient java programmer

A stream pipeline consists of a source, followed by zero or more intermediate operations and a terminal operation.

Untitled Diagram

Stream Source

  • Streams can be created from Collection, Lists, Sets, ints, longs, doubles, arrays, lines of a file

Stream operations are either intermediate or terminal.

  • Intermediate operations such as filter, map or sort return a stream so we can chain multiple intermediate operations.
  • Terminal operations such as forEach, collect or reduce are either void or return a non-stream result.

Intermediate Operations

Zero or more intermediate operations are allowed.

Order matters for large datasets: filter first, then sort or map.

For very large datasets use ParallelStream to enable multiple threads.

Intermediate operations include :

anyMatch()

flatmap()

distinct()

map()

filter()

skip()

findFirst()

sorted()

Terminal Operations

One terminal operation is allowed.

forEach applies the same function to each element.

collect saves the elements into a collection.

Other options reduce the stream to a single summary element.

count() min()
max() reduce()
summaryStatics()

Getting bored ? don’t worry lets try to understand by practical examples :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

        // 1. Integer Stream
        IntStream
                .range(1,10)
                .forEach(System.out::print);
        System.out.println();
    }
}
Output : 123456789

IntStream is one of the stream defined in java.util.stream it will provide all integer in stream.

range(1,10) –  It is intermediate operation which will provide integers  1,2,3,4,5,6,7,8,9

forEach() – Terminal operation which will iterate all integers and system.out::println will print each integer iterated by forEach()

Stream allow use to perform n number of intermediate operations. Lets see the example:

public class JavaStreams {
    public static void main(String[] args) throws IOException {

        // 2. Integer Stream with skip
        IntStream
                .range(1,10)
                .skip(5)
                .forEach(x -> System.out.println(x));
        System.out.println();
    }
}
Output
6
7
8
9

skip(5) will skip first 5 integers which are 1,2,3,4,5

Lets perform addition in the stream

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 3. Integer Stream with sum
        System.out.println(
                IntStream
                        .range(1,5)
                        .sum());
        System.out.println();
    }
}
Output : 10

sum() will add all integers before 5 and starting from 1.

We can sort items very quickly in stream

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 4. Stream.of, sorted and findFirst
        Stream.of("Appu","Aneri","Alberto")
                .sorted()
                .findFirst()
                .ifPresent(System.out::println);
        System.out.println();
    }
}
Output : Alberto

Stream.of() – will convert elements in stream.

sorted() – will sort all elements.

firstFirst() – will find first element of the sorted stream

ifPresent() –  will check if there is any element available in the stream

We can convert array of any elements into stream by Arrays.stream()

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 5. Stream from Array, sort, filter and print
        String[] names = {"Al","Ankit","Kushal","Brent","Sarika","amanda","Hans","Shivika"};
        Arrays.stream(names)
                .filter(x->x.startsWith("S"))
                .sorted()
                .forEach(System.out::println);
        System.out.println();
    }
}
Output : 
Sarika
Shivika

filter() – will only allow names which starts with ‘S’ character.

Lets stream array of integers and perform average of squares :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 6. average of squares of an int array
        Arrays.stream(new int[] {2,4,6,8,10})
                .map(x->x*x)
                .average()
                .ifPresent(System.out::println);
        System.out.println();
    }
}
Output : 44

map(x-> x*x) – will iterate each element and square the value.

average() – calculate average of all elements

We can also get stream from list :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 7. Stream from List, filter and print
        List people = Arrays.asList("Al","Appu","Brent","Sarika","amanda","Hans");
        people
            .stream()
            .map(String::toLowerCase)
            .filter(x -> x.startsWith("a"))
            .forEach(System.out::println);
        System.out.println();
   }
}
Output : 
al
appu
amanda

String::toLowerCase will change case of each element to lowerCase.

We can stream rows from text file and perform needed actions.

Lets create a file name bands.txt and put it in same directory where JavaStreams.java defined.It will contain names of bands and each line will contain only one band name.
File : bands.txt

Rolling Stones
Lady Gaga
Jackson Browne
Maroon 5
Arijit Singh
Elton John
John Mayer
CCR
Eagles
Pink
Aerosmith
Adele
Taylor Swift
Faye Wong
Bob Seger
ColdPlay
Boston
The Cars
Cheap Trick
Def Leppart
Ed Sheeran
Dire Straits
Train
Tom Petty
Jack Johnson
Jimmy Buffett
public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 8. Stream rows from text file, sort, filter and print
        Stream bands = Files.lines(Paths.get("bands.txt"));
        bands
            .sorted()
            .filter(x->x.length()>13)
            .forEach(System.out::println);
        bands.close();
   }
}
Output : 
Arijit Singh
Cheap Trick
Def Leppart
Dire Straits
Jack Johnson
Jackson Browne
Jimmy Buffett
Rolling Stones
Taylor Swift

Files.lines will return stream rows, read each line and put it into stream.

We can get stream rows from text file and save it in list :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 9. Stream rows from text file and save to List
        List bands2 = Files.lines(Paths.get("bands.txt"))
                .filter(x->x.contains("ji"))
                .collect(Collectors.toList());
        bands2.forEach(System.out::println);
        System.out.println();
   }
}
Output : Arijit Singh

Collect –  is terminal operation which will save the filtered stream rows to List.

I hope you people enjoyed reading this. Please write your feedback or queries in the comment box.

Thanks 🙂

Lambda Expression in Java

Lambda expressions are introduced in Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot.

Syntax

A lambda expression is characterized by the following syntax.

parameter -> expression body

Following are the important characteristics of a lambda expression.

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.

  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.

  • Optional curly braces − No need to use curly braces in expression body if the body contains a single statement.

  • Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

Create the following Java Programm LambdaExample.java

public class LambdaExample {

   public static void main(String args[]) {
      LambdaExample lambdaExample = new LambdaExample();
		
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
		
      //with out type declaration
      MathOperation subtraction = (a, b) -> a - b;
		
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
		
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
		
      System.out.println("25 + 10 = " +lambdaExample.operate(25, 10, addition));
      System.out.println("25 - 10 = " +lambdaExample.operate(25, 10, subtraction));
      System.out.println("25 x 10 = " +lambdaExample.operate(25, 10, multiplication));
      System.out.println("25 / 10 = " +lambdaExample.operate(25, 10, division));
		
      //without parenthesis
      GreetingService greetService1 = message ->
      System.out.println("Hello " + message);
		
      //with parenthesis
      GreetingService greetService2 = (message) ->
      System.out.println("Hello " + message);
		
      greetService1.sayMessage("John");
      greetService2.sayMessage("Appu");
   }
	
   interface MathOperation {
      int operation(int a, int b);
   }
	
   interface GreetingService {
      void sayMessage(String message);
   }
	
   private int operate(int a, int b, MathOperation mathOperation) {
      return mathOperation.operation(a, b);
   }
}

It should produce the following output −

25 + 10 = 35
25 - 10 = 15
25 x 10 = 250
25 / 10 = 2
Hello John
Hello Appu

Following are the important points to be considered in the above example.

  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we’ve used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.

  • Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Introduction

Hi Readers,

My name is Govind Singh, born in Barmer, India and have lived in different regions of India. Among them Banglore is my favorite.

In music I love genre like bollywood, punjabi, sufi, old hindi songs, EDM etc.

I work at Decipher Zone Softwares as Software Engineer.I love to explore new technologies, make new friends, event organising and playing football.

I keep updating myself with modern technologies, have hands on experience in Angular, ReactJS, NodeJS, Java, Native Android and Hybrid Mobile Application Development with products like BpmEdge, DocEdge, Gtag, Date Dasher, 3D Observation and counting Nature.

I love to share and gain knowledge and this is the prime reason I started this blog. In this blog I’ll share my industrial experience with Angular, ReactJS, NodeJS and Java.

At last, I love to talk to people so if you have anything that you wants to say or need help with, drop me a mail @ mahechahome@gmail.com

Happy Reading!!! 🙂