Method References in Java 8: Types

 

In Java 8 method references has introduced, which will refer to methods or constructors without invoking them. These syntactic shortcuts create lambdas from existing methods or constructors. Basically, lambda expressions in Java are methods implemented without an enclosing class body and constructors created by lambdas are often referred to as constructor references, which consider to be a subset of method references.

In short, not all methods can be implemented as lambdas. But only those which declared inside candidate functional interface (an interface which contains only one abstract method called as functional interface) are the privileged ones.

So, we will see here how we can convert method parameters based on anonymous implementations of functional interfaces into lambdas:

Any implementation of a Functional interface can be converted to lambda expression.

When we will observe here, all what we need to be done is eliminating the elements which could be implicitly available to the compiler and separating the parameters and the actual expression by “->” operator.

So, one question here arises then when we should go for method references?

Simply we can use method references anywhere we can use Lambda Expressions, which means that a Functional Interface is needed, but only if the Lambda Expression would invoke a single, already defined, method & do nothing else.

The method signature must also match that of the Functional Interface being used. For eg, when used in conjunction with a Predicate, which requires a single input argument & returns a Boolean value, that method would need to accept an argument & return a Boolean value. We will not be able to use method references if we need to invoke more than one method within a Lambda Expression or if we need to pass extra arguments into the method.

In Java 8, we can perform method reference by following 4 types:

1Reference to a static type

package com.code.adda.java8.methodReference.staticMethods;

public class ReferencesToStaticMethodsDemo {
	
	public static void main(String[] args)
	   {
	      new Thread(ReferencesToStaticMethodsDemo::getThreadValue).start();
	      new Thread(() -> getThreadValue()).start();
	      new Thread(new Runnable()
	                 {
	                    @Override
	                    public void run()
	                    {
	                    	getThreadValue();
	                    }
	                 }).start();
	   }

	   static void getThreadValue()
	   {
	      String name = Thread.currentThread().getName();
	      for (int i = 0; i < 8; i++)
	      {
	         System.out.printf("%s: %d%n", name, i);
	        
	         try
	         {
	            Thread.sleep((int) (Math.random()*5));
	         }
	         catch (InterruptedException ie)
	         {
	        	 ie.printStackTrace();
	         }
	      }
	   }
}


Output:


Thread-0: 0
Thread-1: 0
Thread-1: 1
Thread-1: 2
Thread-0: 1
Thread-1: 3
Thread-0: 2
Thread-0: 3
Thread-0: 4
Thread-0: 5
Thread-0: 6
Thread-0: 7
Thread-1: 4
Thread-1: 5
Thread-2: 0
Thread-1: 6
Thread-2: 1
Thread-2: 2
Thread-2: 3
Thread-1: 7
Thread-2: 4
Thread-2: 5
Thread-2: 6
Thread-2: 7


Here, there are three ways to pass a unit of work described by the getThreadValue() method to a new Threadobject whose associated thread is started:

  • It will pass a method reference to the static getThreadValue() method
  • It will pass an equivalent lambda whose code block executes getThreadValue()
  • It will pass an instance of an anonymous class that implements Runnable and runs getThreadValue() method.

2. Reference to an Instance Method of a Particular Object

The object reference on which an instance method is invoked is known as the Receiver of the method invocation.

We can specify the receiver of the method invocation: provide it implicitly when the method is invoked.

a) Bound receiver,

b) Unbound receiver.

a) Bound receiver: it can provide Explicitly when the method is invoked

Syntax: objectRef::instanceMethod

package com.code.adda.java8.methodReference.instanceMethod;

import java.util.function.Function;

public class ReferencesToInstanceBound {
	
	  public Integer factorial(int n) { 	// instance method 
		  if(n==0 || n==1){
			  return 1;
		  }
	    return n * factorial(n-1);
	  }

	  public static void main(String[] args) {
		  
		//using lambda  
		ReferencesToInstanceBound cal = new ReferencesToInstanceBound();
	    Function<Integer, Integer> funLambda = (a) -> cal.factorial(a);
	    System.out.println("By Using lambda expression: "+funLambda.apply(4));

	    // bound type
	    Function<Integer, Integer> funBoundType = cal::factorial;
	    System.out.println("Using a method References To Instance bound type: "+funBoundType.apply(5));

	  }
}

Output:

By References To Instance: 24

References To Instance bound type: 120

b) Unbound receiver:  it can provide implicitly when the method is invoked.

package com.code.adda.java8.methodReference.instanceMethod;

import java.util.function.BiFunction;

public class ReferencesToInstanceUnBound {

	public Integer factorial(int n) { // instance method
		return n == 0 || n == 1?1:n * factorial(n - 1);
	}

	public static void main(String[] args) {

		ReferencesToInstanceUnBound referencesToInstanceUnBound = new ReferencesToInstanceUnBound();
		// using lambda

		BiFunction<ReferencesToInstanceUnBound, Integer, Integer> funLambda = (a, b) -> a.factorial(b);
		System.out.println("By Using lambda expression: " + funLambda.apply(referencesToInstanceUnBound, 5));

		// UnBound type
		BiFunction<ReferencesToInstanceUnBound, Integer, Integer> funUnBoundType = ReferencesToInstanceUnBound::factorial;
		System.out.println("Using a method References To Instance Unbound type: "
				+ funUnBoundType.apply(referencesToInstanceUnBound, 6));

	}
}

Output:

By Using lambda expression: 120

Using a method References To Instance Unbound type: 720


BiFunction<T,U,R> : Represents a function that accepts two arguments and produces a result. This is the two-arity specialization of Function.

Ref:  https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html

3. Reference to an instance method of an arbitrary object of a particular type

Syntax :  ContainingType::methodName

package com.code.adda.java8.methodReference.instanceMethodArbitrary;

import java.util.function.Function;

interface Factorial {
	default int calculate(int n) {
		return n == 0 || n == 1 ? 1 : n * calculate(n - 1);
	}
}

public class ReferenceToInstanceArbitraryObj implements Factorial {

	@Override
	public int calculate(int n) { // calculate Fibonacci series using recursion
		return n <= 1 ? n : calculate(n - 1) + calculate(n - 2);

	}

	public void calculateValue(int value) {
		// By Using Uses this::calculate method
		Function<Integer, Integer> function1 = this::calculate;
		System.out.println("this::calculate(): Fibonacci Series = ");
		for (int i = 0; i <= value; i++) {
			System.out.print(function1.apply(i) + " ");
		}
		// By Using Factorial.calculate() method
		Function<Integer, Integer> function2 = Factorial.super::calculate;
		System.out.println("\nFactorial::calculate(): Factorial = " + function2.apply(value));
	}

	public static void main(String[] args) {
		ReferenceToInstanceArbitraryObj obj = new ReferenceToInstanceArbitraryObj();
		obj.calculateValue(6);
	}
}

Output:

this::calculate(): Fibonacci Series = 0 1 1 2 3 5 8

Factorial::calculate(): Factorial = 30

4. Reference to a constructor

Syntax:  ClassName::new

package com.code.adda.java8.methodReference.toConstructor;

@FunctionalInterface
interface ISquare {
	Square getSquare(int fact);
}

class Square {
	public Square(int n) {
		System.out.print("Sqauare Value by Reference to a constructor: " + n * n);
	}
}

public class MethodRefToCnstructor {

	public static void main(String[] args) {
		ISquare sqr = Square::new;
		sqr.getSquare(6);

	}

}

Output:

Sqauare Value by Reference to a constructor: 36

Share Knowledge
Posted in Java 8 | Tagged , , | Leave a comment

How to solve – Could not find a part of the path bin roslyn csc.exe error

If you are trying to run Asp.Net application and getting given error in your browser even after successfully build and compile without getting any error.

Don’t worry! this is all happening because your build is trying to find \bin\roslyn\csc.exe because following packages have been added in your project. Just review you packages.config file, you can have both of them there.

Continue reading

Share Knowledge
Posted in C#, TIPS/TRICKS | Tagged , , , , | Leave a comment

Consuming RESTful API to get Bank Details using IFSC code in C#

Introduction

Suppose If you assigned the task to write code to get bank details using IFSC code. Details may be bank name, ifsc code, micr(Magnetic Ink Character Recognition), branch, address, contact, city, district and state. What you’ll do ?

All bank ifsc codes are regularly updated on RBI website, you can download in Excel sheet and re arrange it. and same can be used in your website but this is not easy task to gather such a large data and integrate in your database to get details. So you just need only a RESTful API to accomplish this task but unfortunately there is no such API which can provide updated details.  ifsc cods are obtain from different banks by RBI  every month, new banks branches are go to add every time . so technically its very hard to maintain the all bank IFSC list.

Continue reading

Share Knowledge
Posted in C#, TIPS/TRICKS, WEB API | Tagged , , , | 5 Comments

How To Enable SSL or HTTPS In Apache Tomcat 8

In this article we are going to see how to enable SSL in Apache Tomcat Server 8 and automatic redirect http to https. All we need is a Self-Signed-Certificate and do some configurations. There are many tools/utilities available to generate the certificate. We will be using KEYTOOL which comes along with JDK installation. Let us know few terminologies first.

Self-Signed Certificate:

  • A certificate that is signed by itself rather than a trusted authority.
  • Generally used for testing purpose only.

SSL (Secure Sockets Layer):

  • A standard way of establishing an encrypted link between a web server and a browser.
  • Ensures that all data passed between the web server and browsers remain private and integral.

Hyper Text Transfer Protocol Secure (HTTPS):

  • HTTPS is the secure version of HTTP.
  • The protocol over which data is sent between your browser and the website that you are connected to.

 

Generate Self-Signed-Certificate with java keytool

We will use keytool command to generate the self-signed-certificate. When invoking the command on cmd, you will be asked to fill different details related to certificate. Following keytool command will generate the certificate in currently logged in user’s directory. (say: C:\Users\Chandra Mani\keystore.jks).

Continue reading

Share Knowledge
Posted in Java | Tagged , , , , | Leave a comment

Method Reference in Java 8

In the place of an Anonymous class we can use Lambda expression but Sometimes, the lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by its name.

List digits = Arrays.asList(&amp;amp;quot;1&amp;amp;quot;,&amp;amp;quot;2&amp;amp;quot;,&amp;amp;quot;3&amp;amp;quot;,&amp;amp;quot;4&amp;amp;quot;,&amp;amp;quot;5&amp;amp;quot;,&amp;amp;quot;6&amp;amp;quot;,&amp;amp;quot;7&amp;amp;quot;,&amp;amp;quot;8&amp;amp;quot;);
List numbers = map(n -&amp;amp;gt; new Integer(n), digits);

Method references enable you to do this; A method reference is a shorthand syntax for a lambda expression that executes only One method. We can Use it if we need to declare fields or additional methods.

Syntax :   Object :: methodName

List digits = Arrays.asList(&amp;amp;quot;1&amp;amp;quot;,&amp;amp;quot;2&amp;amp;quot;,&amp;amp;quot;3&amp;amp;quot;,&amp;amp;quot;4&amp;amp;quot;,&amp;amp;quot;5&amp;amp;quot;,&amp;amp;quot;6&amp;amp;quot;,&amp;amp;quot;7&amp;amp;quot;,&amp;amp;quot;8&amp;amp;quot;);
List numbers = map(Integer::new, digits);

 

Note:

  • In the place of an Anonymous class we can use Lambda Expression,
  • In the place of a lambda expression where it calls only one method on that time we can use Method Reference.
  • Basically, Lambdas interface can contain only a single abstract method. It will fail as your interface contains more than one abstract method. In such cases anonymous classes will be most significant to use.
  • In java 8, anonymous classes can be use directly by using new java 8 type annotation:
    @MyTypeAnnotation InterfaceName() {};

There are four types of method references in Java 8:

  1. Reference to a static method,
  2. Reference to an instance method of a particular object,
  3. Reference to an instance method of an arbitrary object of a particular type,
  4. Reference to a constructor.

 

Types Syntax Example
(Using Lambda expression)
Example
(Using Method Reference)
Reference to a static method ContainingClass::staticMethodName s-> String.lastIndexOf(s) String::lastIndexOf
Reference to an instance method of a particular object containingObject::instanceMethodName () -> “value”.toString() v:toString
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName s-> s.toString() String::toString()
Reference to a constructor ClassName::new String::new () -> new String()

 

Share Knowledge
Posted in Java 8 | Tagged , , | 1 Comment