How to better use method reference in Java 8

preface

A method reference is an existing method or constructor used to directly access a class or instance. Method references provide a way to reference without executing a method, which requires a target type context composed of compatible functional interfaces. When evaluated, the method reference creates an instance of the functional interface.

When only one method call is executed in a lambda expression, it is more readable to directly use the form of method reference without lambda expression. Method reference is a more concise and understandable lambda expression.

Note: the method reference is a lambda expression, where the operator of the method reference is a double colon ":".

In Java 8, it is very simple to use a method reference, such as string:: isempty, but its negative method reference cannot be used. The content of this article is how to solve this problem so that we can use method reference more comprehensively.

Let's first look at an example of using method references:

The output of the above code is 1, that is, the number of empty strings. If we want to get the number of non empty strings, we can't use method references directly.

The predicate in Java 8 has a predicate Negate() can be converted to the negative form of an assertion, but string:: isempty cannot (string:: isempty. Negate() or! String::isEmpty )。 Because a method reference is not a lambda or function interface, it can be resolved to one or more function interfaces. For example, string:: isempty can be parsed at least as follows:

In order to solve the above problems, we can explicitly convert the method reference into a function interface through some mechanism:

By using a static method, accepting method reference parameters and returning a function interface, the conversion from method reference to function interface can be realized. Then, we can use the method reference to obtain the number of non empty strings in the above example.

Furthermore, various combinations of predict can be used.

Since a method reference may be resolved to multiple function interfaces, it is easy to cause confusion if we implement many as methods with different parameters. A better way is to add the type of function parameter to the method name to distinguish.

Original English: https://dzone.com/articles/put-your-java-8-method-references-to-work

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>