Saturday, August 18, 2018

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

DoubleBinaryOperator 

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));
	}
}
35.0
70.0

IntBinaryOperator

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.

Example

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

LongBinaryOperator

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.

Example

LongBinaryOperator sumOperator= (p, q) -> p + q;
		System.out.println(sumOperator.applyAsLong(15, 25));
The output of the above code execution is
40
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. 
Syntax
@FunctionalInterface
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
120
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;
	      System.out.println(sum1.apply(25,35));      
	}
}
Output is
120
60

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
45
50

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(
Comparator.naturalOrder());
BinaryOperator<Integer> reverseOrderMax = BinaryOperator.maxBy(
Comparator.reverseOrder());
System.out.println(naturalOrderMax.apply(50, 45));
System.out.println(reverseOrderMax.apply(50, 45));
Output of above code is
50
45
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));
console.log(convertEmployObjectToJsonString('Ram'));
console.log(convertEmployObjectToJsonString());
console.log(convertEmployObjectToJsonString(null,null));
Output is
{"name":"Frank","salary":6000}
{"name":"Ram","salary":5000}
{"salary":5000}

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.
Syntax

function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
   statements
}
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));
console.log(convertEmployObjectToJsonString('Ram',''));
console.log(convertEmployObjectToJsonString());
console.log(convertEmployObjectToJsonString(null,null));
console.log(convertEmployObjectToJsonString('asdfads',null));
console.log(convertEmployObjectToJsonString('Ram','undefined'));
output is
{"name":"Frank","salary":6000}
{"name":"Ram","salary":""}
{"salary":5000}
{"name":null,"salary":null}
{"name":"asdfads","salary":null}
{"name":"Ram","salary":"undefined"}

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}`);
}
console.log(funcObject({
  name: 'kiran'
})); 
console.log(funcObject({})); 
The output of the above code
kiran, 5000
Frank, 5000

Read More

Java8 - UnaryOperator interface Examples | Functional Interfaces tutorials

java.util.function.UnaryOperator

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

@FunctionalInterface
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;
System.out.println(unaryOperator.apply(6));
System.out.println(unaryOperator.apply(6));
Output is
49
16

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();
System.out.println(IdentityUnaryOperator.apply(25));
output is
25

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;
System.out.println(UnaryOperator1.andThen(UnaryOperator2).apply(3));
System.out.println(UnaryOperator1.compose(UnaryOperator2).apply(3));
The output of the above code execution is
90
900

Method Reference Example 

This is an example of a functional interface used with method reference
UnaryOperator<String> methodRef = String::toLowerCase;
System.out.println(methodRef.apply("CLOUDHADOOP"));
Output is

cloudhadoop

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;
System.out.println(IncrementInteger.applyAsInt(9));
The output of the above code is
10

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;
System.out.println(decrementLong.applyAsLong(998756));
Output is
998757

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;
System.out.println(doubleUnaryOperatorExample.applyAsDouble(5));
System.out.println(doubleUnaryOperatorExample.applyAsDouble(25.2));
Output is
10.0
50.4
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.
IntConsumer
LongConsumer
DoubleConsumer
Consumer is an operation that accepts numeric values and outputs no result.
In my previous post, documented consumer tutorials.

IntConsumer

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);
consumer.accept(51);
consumer.accept(110);
int[] numbers = {8,7,3,1};
IntConsumer intConsumerFunction = value -> System.out.print(value+" ");
Arrays.stream(numbers).forEach(intConsumerFunction);
Output is
51
110
8 7 3 1 

LongConsumer

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); }; 
longConsumer1.accept(5);
LongConsumer longConsumer2 = ( value) -> { System.out.println(value); }; 
longConsumer1.andThen(longConsumer2).accept(4);
Output is
5
4
4

DoubleConsumer

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);
multiplyDoubleConsumer.accept(.5);
Output is
0.25

Read More

Java8 Primitive Supplier Examples | Functional Interface tutorials

Primitive Supplier Examples

java.lang.function package provides various primitive supplier interfaces. java8 has functional interfaces for different data types like integer, long, double and boolean. This post explains various primitive supplier and usage examples.
All these interfaces can be assigned with lambda expressions and method/constructor reference.
The Element class is used in all interface examples.

package org.cloudhadoop.functions;
public class Element {

 private Boolean enabled;
 private Integer number;

 public Element(Integer number, Boolean enabled) {
  this.enabled = enabled;
  this.number = number;
 }

 public Boolean getEnabled() {
  return enabled;
 }

 public void setEnabled(Boolean enabled) {
  this.enabled = enabled;
 }

 public Integer getNumber() {
  return number;
 }

 public void setNumber(Integer number) {
  this.number = number;
 }
}

IntSupplier

java.util.function.IntSupplier interfaces is used as a supplier for integer result.
It has single abstract method getAsInt() returns integer value.
IntSupplier intSupplier = ()-> 20;
System.out.println(intSupplier.getAsInt());
Element element = new Element(87,false);
IntSupplier intSupplier1 = element::getNumber; 
System.out.println(intSupplier1.getAsInt());
Output is
20
87

DoubleSupplier

java.util.function.DoubleSupplier interfaces are used as a supplier for a double result. It has single abstract method getAsDouble() returns the double result.
DoubleSupplier doubleSupplier = ()-> 15;
System.out.println(doubleSupplier.getAsDouble());
Element element = new Element(14,false);
DoubleSupplier doubleSupplier1 = element::getNumber; 
System.out.println(doubleSupplier1.getAsDouble());
Output is
15.0
14.0

LongSupplier

This interface is defined in java.util.function and used as a supplier for the long result. It has single abstract method getAsLong() returns long values.
LongSupplier longSupplier = ()-> 25l;
System.out.println(longSupplier.getAsLong());
Element element = new Element(24,false);
LongSupplier longSupplier1 = element::getNumber; 
System.out.println(longSupplier1.getAsLong());

Output is
25
24

BooleanSupplier

This interface is used as a supplier for boolean values. It has only one abstract method getAsBoolean return boolean value result.
 BooleanSupplier booleanSupplier = ()-> false;
System.out.println(booleanSupplier.getAsBoolean());
Element element = new Element(124,true);
BooleanSupplier booleanSupplier1 = element::getEnabled; 
System.out.println(booleanSupplier1.getAsBoolean());
output is
false
true
Read More