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
Stream and types of Streams
A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are:

Byte Streams: Provide a convenient means for handling input and output of bytes. Byte Streams classes are defined by using two abstract classes, namely InputStream and OutputStream.

Character Streams: Provide a convenient means for handling input & output of characters. Character Streams classes are defined by using two abstract classes, namely Reader and Writer.
Famous Quotations
The very best thing you can do for the whole world is to make the most of yourself.
-- Wallace Wattles

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.