Saturday, August 18, 2018

ES 6 features - destructuring assignment examples| Learn Es6 tutorials

Es6 introduced a new feature called destructuring assignment. This is a syntax change to extract the data from objects or array and assigned to variables.

Destructuring assignment Basics

First get the right side of the equal sign. ie arrays/objects and break or destruct it, and assign this each part to each corresponding variable on the left side of the equal sign. Here Variables are already existed or can be created using let const and var keywords.

Prior to es6 and previous javascript versions

Declared and initialized an array with two values.
let arrayExample = ["destructuring", "assignment"]
Now we want to retrieve the values from an array and assign to variables, Used index with getting an element from an array
let firstElement = arrayExample[0];
let secondElement = arrayExample[1];
The same code can be rewritten with destructuring assignment syntax as follows
let arrayExample = ["destructuring", "assignment"]
let [firstElement, secondElement] = arrayExample;
Output the above code execution is

Array Destruction assignment

Arrays are a a group of elements store under a name.By now you understand destruction feature.Array destruction, left the side of the element is an array value and breaks the array and assign to the same variables order with the same array index.

Basic Example

var var1, var2;
[var1,var2] = [15, 12];
console.log(var1); // 15
console.log(var2); // 12

Default values with destruction

if the number of variables declared on the left side is more than a number of elements in the right side, then excess items are not assigned. variables with default values are mapped to the values from Array. if no matching index element found in array, Default values are initialized.
const [var1 = 'defaultone', var2, var3 ='defaulthree'] = arrayExample;
console.log(`var1: ${var1}, var2: ${var2}, var1: ${var2}`);
Output is
var1: one, var2: undefined, var3: defaulthree
var1 and var3 has default parameter values,
the array has only one index element, the First element is assigned to var1, var2 is assigned with undefined, var3 assigned with a default value

Skip variables initialization

let [, , testvar] = ["one", "two", "three", "four"];
console.log( testvar ); 
In the above example, Two commas are placed, Each comma represent single unknown variable
output is

Object Destruction assignment Examples

The object is a composition of different attributes store under a single name. The right-hand side of an equal operator is Object and destruct/break it and assigned with variables
In the below code, the simple variable is declared assigned to the value, Please note, Id is not mentioned on the right-hand side in a code Using destruction.
var employee = {
    id: 12,
    name: "Frank"
var { id } = employee; 
var { name } = employee;
console.log(id);      // outputs 12
console.log(name);      // outputs Frank

Object Default values

Variables declared in the left side should be declared with default values
var employee = {
    id: 11,
    name: "Tom"
var newEmployee = {};
var { id: newId = 12 } = newEmployee;
console.log(newId);      // 12

Here newEmployee is empty and local variable newId is created and the default value is 12, if id property not found in the object, the newId value is assigend with a default value. In this case id property not existin object. Out put is 12
var { id: newId = 12 } = employee;
console.log(newId);      // 11

a local variable is created with id value from the object, property id exists in the object, so id value is assigned to local variable output is 11 for new id

new variable names assignment

Normally you create a same variable name of the object properties.
In this example, You are going to create a new variable with a different name, assigned with object property
It creates a new local variable newId that is assigned with
newId is initialized with value 11
If you access id variable, throws error 'Uncaught ReferenceError: id is not defined'
var employee = {
id: 11,
name: "Tom"
var { id: newId } = employee;
console.log(newId); // "Identifier"
console.log(id); // outputs 12

Nested Object destruction

An object has child object as shown below example
var employee = {
    id: 11,
    name: "Tom",
    address: {
        city: 'NewYork',
var { address: { city} } = employee;
console.log(city);      // outputs Newyork
console.log(address);       // error: address is undefined
Here, city local variable is created and assigned with NewYork, address variable is not created and serving the locators for mapping child elements.
Destructuring looping/iteration

Object.entries method is used to destructuring/break the key and pair values of an object during an iteration of for loop
var employee = {
    id: 51,
    name: "John",
for (let [key, value] of Object.entries(employee)) {
  console.log(`${key}:${value}`); // id:51 name:John

REST operator with the destructuring assignment

Rest/Spread operators introduced in Es6 with the new syntax. This can be used to assign to variables with destructing
let [var1, var2, ...varRest] = ["one", "two", "three", "four","five"];
console.log(var1); // one
console.log(var2); // two
console.log(varRest[0]); // three
console.log(varRest[1]); // four
console.log(varRest[1]); // five
console.log(varRest.length); // 3

destructuring parameters from the object passed a function's parameters

destructuring the id and name from an object that is passed as an argument to function.
var employee = {
    id: 11,
    name: "Tom",
function getEmployee({name, id}) {
  console.log('id: '+id + '  name: ' + name);

Read More

Java8 - Numeric BinaryOperator interface examples | Functional Interfaces tutorials

In my previous post, discussed BinaryOperator tutorials with examples
Numeric BinaryOperators are declared in java.util.function package. Each numeric primitive types like long, int and double have binary operators. Binary Operators are operators that take two parameters of primitive type and outputs the same primitive type values


It is a functional interface that takes two double values as input and output double value. It is a double version of BinaryOperator. It has a single abstract method - applyAsDouble(T, V) T and V are two input parameters and return the result of double.

Lambda Expression and Method reference example 

The below code showcase the usage of DoubleBinaryOperator with lambda/Method reference

package org.cloudhadoop.functions;
import java.util.function.DoubleBinaryOperator;
public class MyDoubleBinaryOperatorExample {
	public static double mutiply(double d1, double d2) {
		return d1 * d2;
	public static void main(String[] args) {

		// Using Lambda Expression
		DoubleBinaryOperator lamdaExample = (v1, v2) -> MyDoubleBinaryOperatorExample.mutiply(v1, v2);
		System.out.println(lamdaExample.applyAsDouble(5, 7));
		// Using Method reference
		DoubleBinaryOperator methodRefExample = MyDoubleBinaryOperatorExample::mutiply;
		System.out.println(methodRefExample.applyAsDouble(35, 2));


It is Integer version of BinaryOperator defined in java.util.function, which takes two integer values as input and output integer-only. It has only one abstract applyAsInt() method.


IntBinaryOperator sumOperator= (p, q) -> p + q;
System.out.println(sumOperator.applyAsInt(35, 41));
Output is


It is a long version of BinaryOperator defined in java.util.function. This is an operation takes two long values as input and produces an output of long. It has only one abstract applyAsLong() method.


LongBinaryOperator sumOperator= (p, q) -> p + q;
		System.out.println(sumOperator.applyAsLong(15, 25));
The output of the above code execution is
Read More

Friday, August 17, 2018

Java8 - BinaryOperator interface examples | Functional Interface tutorials

BinaryOperator is an interface defined in java.util.function package of java8. This interface extends BiFunction interface. This can be assigned with Lamda expressions/method references This performs an operation that accepts two parameters of the same type and returns the same type value as a result. In this post, We are going to learn BinaryOperator interface and it's method usage and examples. 
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator)
public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) 
There is no direct abstract method in this. Two static methods - minBy, maxBy are defined in BinaryOperator. BiFunction has a single abstract method - R apply(T t, U u);

 Lambda Expression Example 

Lambda expression has only two parameters - (v1, v2) and Lambda expression is assigned to BinaryOperator function
BinaryOperator<Integer> sum = (v1, v2) -> v1 + v2;
		System.out.println(sum.apply(50, 70));
		BinaryOperator<String> appendString = (str1, str2) -> str1 + str2;
		System.out.println(appendString.apply("Binary ", "Operator Example "));
Output of the above code is
Binary Operator Example 

Method reference example 

a static method is declared and this method is called using a double colon:: operator. The below is an example code for method reference usage
package org.cloudhadoop.functions;
import java.util.function.BinaryOperator;
public class MyBinaryOperatorExample {
	public static Integer sum(int m,int n) {
	     return m+n;
	public static void main(String[] args) {
		  //  lambda expression Example
		BinaryOperator<Integer> sum=(v1, v2) ->sum(v1 , v2);
		System.out.println(sum.apply(50, 70));
		  //  Method reference Example
		BinaryOperator<Integer> sum1= MyBinaryOperatorExample::sum;
Output is

Static minBy() method Example 

minBy() method is a static method defined in java.util.function.BinaryOperator class.  It returns Binary Operator which works in return low of given value based on the provided comparator
BinaryOperator<Integer> naturalOrderMin = BinaryOperator.minBy(
Comparator.naturalOrder()); // Natural Order Comparator passed
BinaryOperator<Integer> reverseOrderMin = BinaryOperator.minBy(
Comparator.reverseOrder()); // Reverse Order Comparator passed
System.out.println(naturalOrderMin.apply(50, 45));
System.out.println(reverseOrderMin.apply(50, 45));
Output is

maxBy() method Example

It is a static method which returns BinaryOperator - which does a maximum of given values with comparator provided
BinaryOperator<Integer> naturalOrderMax = BinaryOperator.maxBy(
BinaryOperator<Integer> reverseOrderMax = BinaryOperator.maxBy(
System.out.println(naturalOrderMax.apply(50, 45));
System.out.println(reverseOrderMax.apply(50, 45));
Output of above code is
Read More

Learn ES6 - Default Parameters | ecmascript 6 Tutorials and examples

In this Post, We are going to learn the es6 features -Default arguments to the function tutorials with examples.
Prior to Es6 Java version, The following is the way to handle default parameter values.

ES5 Default Parameters and previous javascript versions

Declared a convertEmployObjectToJsonString function to convert the Employee arguments to JSON string, has two arguments - name and salary
The name is a required argument
Salary is optional parameters
salary argument is an optional parameter. When salary argument is not passed, the default value is assigned with 5000.
function convertEmployObjectToJsonString(name,salary){
    salary = (typeof salary !== 'undefined') ? salary : 5000;
    return JSON.stringify({'name':name,'salary':salary});
console.log(convertEmployObjectToJsonString('Frank', 6000));
Output is

When convertEmployObjectToJsonString is called, salary argument is not passed means undefined, the Default value is 5000. We have added the check for salary arguments for the undefined case and if it is undefined, the the default value is initialized.

ECMAScript 2016 Default parameters 

Default parameters are syntax change to the function parameters Es6 is a new javascript version changes Default parameters declared in functional parameters initialized with a a default value when the parameter to the function is undefined or not passed.

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
The same above example is rewritten using es6 default parameters
function convertEmployObjectToJsonString(name,salary=5000){
    return JSON.stringify({'name':name,'salary':salary});
console.log(convertEmployObjectToJsonString('Frank', 6000));
output is

Points to Remember 

In javascript, Arguments to functions default to undefined, This allows changing the different value. When valid values are passed as arguments, Default parameters have not initialized any value, empty and null are considered valid values, Undefined, the value is not passed, the argument to the function is not passed, undefined value is considered, the default value is initialized with default value Default arguments are evaluated at called time.
Please map the above results with this points to have a good understanding.

Function as default parameter example 

Here Function next is declared inside the body of the getValues function. getValues has default parameters as a Function. The order of the execution is as follows.
Default parameters always run first. Nested Function declared in function body are executed next. When getValues() method is called with a function parameter, the function declaration is not available so the below code throws an error - Uncaught ReferenceError: next is not defined So the takeaway point is, Functions declared inside other function body are not passed as default arguments.
function getValues(value = next()) {
  function next() { return 'next function method'; }
Fix/ solution for ReferenceError is to move the inside function to global or outside scope.
function next() { return 'next function method'; }

function getValues(value = next()) {

Default parameters Destructuring Assignment example

 Default parameters can also be used with Destruction assignment. Destruction assignment is a new kind of syntax introduced in ES6 and expression to retrieve values from arrays and objects and assigned to variables.

Destruction assignment example

var value1, value2;
[value1, value2] = [30, 50]; // outputs value1=30 and value2=50
[value1=4, value2=value1] = [];     // value1=4;value2=4
[value1=5, value2=value1] = [6];    // value1=6; value2=6
[value1=3, value2=value1] = [3,5]; // value1=3; value2=5
here is an example of destruction assignment as a default parameter in a function declaration
function func([a, b] = [5, 6], {c: c} = {c: 2}) { 
  return a + b + c; 
console.log(func()); // outputs 13

Destructured Object assignment example 

Default parameters can also be declared with Object destructuring assignment. The following is an example for usage of Object destruction
function funcObject ({
    name = 'Frank',
    salary = 5000
  } = {}) {

  return (`${name}, ${salary}`);
  name: 'kiran'
The output of the above code
kiran, 5000
Frank, 5000

Read More

Java8 - UnaryOperator interface Examples | Functional Interfaces tutorials


UnaryOperator is a functional interface in java.util.function package It operates on one operand and return the result of same operand type. This are assigned with lambdaexpressions/metod/constructor references

UnaryOperator code signature

public interface UnaryOperator<T> extends Function<T, T> {  
    static <T> UnaryOperator<T> identity() {
        return t -> t;
UnaryOperator extends Function interface, It extends abstract apply from the functional interface. Function Interface has default andThen() and compose methods

Lamda UnaryOperator method example 

This is an example of using UnaryOperator usage with lambda expressions
UnaryOperator<Integer> unaryOperator = value -> value* value;
Output is

Static Identity method example 

It has an only static method, which returns the input value. Below is an example for usage of this method
UnaryOperator<Integer> IdentityUnaryOperator = UnaryOperator.identity();
output is

Default methods andThen compose example 

This method extended from the Function interface. The difference between andThen and compose is the order of the parameter execution andThen - Run the called function first and parameter last compose - Run the parameter first and called function last
UnaryOperator<Integer> UnaryOperator1 = value -> value * value;
UnaryOperator<Integer> UnaryOperator2 = value -> value * 10;
The output of the above code execution is

Method Reference Example 

This is an example of a functional interface used with method reference
UnaryOperator<String> methodRef = String::toLowerCase;
Output is


Primitive Unary Operators.

There are three primitive unary operators for Integer, Long and Double. All these contain only single abstract method. All these operators take corresponding value types and output same output type values. All this can be assigned with lambda expressions, passed arguments, method references All are defined in java.util.function package. All this will be used as a single arguments

IntUnaryOperator usage example 

It has an only single abstract method - applyAsInt It is a functional interface and takes an integer value and produces integer only
IntUnaryOperator IncrementInteger = (value) -> value +1;
The output of the above code is

LongUnaryOperator  interface usage

This is a functional interface and takes long as input and outputs long value only And the single abstract method is applyAsLong
LongUnaryOperator decrementLong = (value) -> value + 1;
Output is

DoubleUnaryOperator Usage Example

 DoubleUnaryOperator takes the double value and output double value only. This has only one abstract method - double applyAsDouble(double operand); Default methods - andThen, compose methods
DoubleUnaryOperator doubleUnaryOperatorExample = (value) -> value+value;
Output is
Read More

Thursday, August 16, 2018

Java8 Primitive Consumer Interface examples| Functional Interface tutorials

java.util.function.consumer Interface 

Java 8 introduced different consumer interfaces in java.util.function package.
Consumer is an operation that accepts numeric values and outputs no result.
In my previous post, documented consumer tutorials.


It has an only single abstract method - accept() which takes an input value and returns nothing
And also default method - andThen(IntConsumer after) - Returns aggregation consumer of called consumer with after consumer result
IntConsumer consumer = value -> System.out.println(value);
int[] numbers = {8,7,3,1};
IntConsumer intConsumerFunction = value -> System.out.print(value+" ");;
Output is
8 7 3 1 


LongConsumer interface is defined in java.util.function package in java8 language. it takes long input value and output no result.
It has only one abstract method -accept()
Default method - andThen(LongConsumer after) - returns aggregate compose consumer of called consumer with the operation of after result consumer

accept and andthen Example
LongConsumer longConsumer1 = ( value ) -> { System.out.println(value); }; 
LongConsumer longConsumer2 = ( value) -> { System.out.println(value); }; 
Output is


DoubleConsumer is an inbuilt interface defined in java.util.function package in java8. This has only accept abstract method, takes a double value and produces no output
And also andThen default method
DoubleConsumer multiplyDoubleConsumer= (value) -> System.out.println(value*value);
Output is

Read More