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
What is servlet context?
The servlet context is an interface which helps to communicate with other servlets. It contains information about the Web application and container. It is kind of application environment. Using the context, a servlet can obtain URL references to resources, and store attributes that other servlets in the context can use.
Famous Quotations
If you don’t make mistakes, you’re not working on hard enough problems. And that’s a big mistake.
-- Frank Wilczek

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.