JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Lambda example with single method interface implementation.


Functional interfaces are an interface with single abstract method. Lambdas are type of functional interfaces. Java API has many single method implementations like Comparator, Runnable, Callable, etc. Prior to Java-8, you can implement and initiaize them using anynomus class syntax.

In this page we have given a simple example on Lambda implementation on single method interface. We have taken Runnable interface for the example. It has only one method called "run". In the example notice that how lambda reduced multiple lines of code to single line:

package com.java2novice.lambda;

public class FuncIntLambdaEx {

	public static void main(String a[]) {

		// normal way of anonymous class implementation
		Runnable rnnObj = new Runnable() {

			@Override
			public void run() {
				System.out.println("Runnable interface with normal anonymous class implementation...");
			}
		};

		// anonymous class implementation with Lambda
		Runnable rnnObjLImpl = () -> System.out.println("Runnable interface with Lambda implementation...");

		rnnObj.run();
		rnnObjLImpl.run();
	}
}

Output:
Runnable interface with normal anonymous class implementation...
Runnable interface with Lambda implementation...
<< Previous Program | Next Program >>

Java-8 Lambda expression examples

  1. Lambda expression syntax example
  2. Lambda example with single method interface implementation.
  3. Comparator example with Lambda implementation.
  4. How to return lambda as an object?
Knowledge Centre
Can you list serialization methods?
Serialization interface does not have any methods. It is a marker interface. It just tells the JVM that your class can be serializable.
Famous Quotations
I respect faith, but doubt is what gets you an education.
-- Wilson Mizner

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.