Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a method reference for a no-op (NOP) that can be used for anything lambda?

This may sounds like a strange question, but is there a way to refer to a standard no-op (aka null operation, null-pattern method, no-operation, do-nothing method) method for a Lambda in Java 8.

Currently, I have a method that takes a, say, void foo(Consumer<Object>), and I want to give it a no-op, I have to declare:

foo(new Consumer<Object>() {    public void accept(Object o) {      // do nothing    } } 

where I would like to be able to do something like:

foo(Object::null) 

instead. Does something like exist?

Not sure how that would work with multi-parameter methods -- perhaps this is a deficiency in the lambdas in Java.

like image 761
Ben Avatar asked Apr 24 '15 15:04

Ben


People also ask

Why method reference is better than lambda?

The method references can only be used to replace a single method of the lambda expression. A code is more clear and short if one uses a lambda expression rather than using an anonymous class and one can use method reference rather than using a single function lambda expression to achieve the same.

What method can you use to apply a given instance of consumer to all the elements of a collection?

The forEach method accepts a Consumer as a parameter. The consumer can be simplified with a lambda expression or a method reference. In the example, we go over the elements of a list with forEach . The consumer simply prints each of the elements.

Which code uses a method reference correctly?

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

WHAT ARE method references?

Method references are a special type of lambda expressions. They're often used to create simple lambda expressions by referencing existing methods. There are four kinds of method references: Static methods. Instance methods of particular objects. Instance methods of an arbitrary object of a particular type.


1 Answers

This is no deficiency.

Lambdas in Java are instances of functional interfaces; which, in turn, are abstracted to instances of Java constructs which can be simplified to one single abstract method, or SAM.

But this SAM still needs to have a valid prototype. In your case, you want to have a no-op Consumer<T> which does nothing whatever the T.

It still needs to be a Consumer<T> however; which means the minimal declaration you can come up with is:

private static final Consumer<Object> NOOP = whatever -> {}; 

and use NOOP where you need to.

like image 152
fge Avatar answered Oct 05 '22 08:10

fge