Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of Java8 functional programming

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Most people do not understand the knowledge points of this article "what is the Java8 functional programming method?", so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what is the Java8 functional programming method" article.

What is functional programming?

Functional programming is a programming paradigm with a high degree of abstraction. Functions written in pure functional programming languages have no variables. Therefore, for any function, as long as the input is definite, the output is definite. This kind of pure function is called without side effects. In programming languages that allow the use of variables, because the state of variables within the function is uncertain, the same input may get different outputs, so this function has side effects. One of the features of functional programming is that it allows the function itself to be passed into another function as an argument, as well as to return a function! Functional programming was first a set of functional transformation logic studied by mathematician Alonzo Qiuqi, also known as Lambda Calculus (λ-Calculus), so functional programming is often called Lambda computing.

Java8 has built-in some commonly used method interfaces FunctionalInterface

This interface defines only one abstract method and is marked with @ FunctionalInterface annotations, such as Predicate,Consumer,Function,Supplier,Comparator, etc., which belong to the java.util.function package

@ FunctionalInterfacepublic interface Predicate {boolean test (T t);} @ FunctionalInterfacepublic interface Consumer {void accept (T t);} / omitted

Their characteristic is that they define the input parameters and return values of the function. When they are used, they pass an expression that satisfies the definition of the function interface, which can be checked by the compiler. The function interface and the corresponding four ways of use are described below.

Through an example to see the difference between using a function and not using it, the requirement is to have a function, pass in a List, filter out odd-numbered items, and the other filter out even-numbered items. First, look at the writing that does not use functions.

/ / filter the singular method public static List filterSingular (List list) {List result = new ArrayList (); for (Integer item: list) {if (item% 2! = 0) {result.add (item);}} return result } / / the even-numbered method public static List filterEven (List list) {List result = new ArrayList (); for (Integer item: list) {if (item% 2 = = 0) {result.add (item);}} return result;}

Called after the method is defined, the expected effect output [1mem3pd5pd7] and [2pd4pr5]

List targetList = new ArrayList () {{this.add (1); this.add (2); this.add (3); this.add (4); this.add (5); this.add (6); this.add (7) }}; List singularList = filterSingular (targetList); List evenList = filterEven (targetList); System.out.println (singularList); System.out.println (evenList)

But in fact, the only difference between the two filter functions is that the judgment condition is different. At this time, this condition can be abstracted as a function interface to write. The test definition of the Predicate interface begins with passing in a generic type, returning a boolean, and rewriting the filter code.

Public static List filter (List list,Predicate predicate) {List result = new ArrayList (); for (Integer item: list) {if (predicate.test (item)) {result.add (item);}} return result;}

The function is transformed into an instance object that implements the Predicate interface in addition to the current List. You only need to pass in the input and output parameters to meet the definition of the function, and it can be compiled. Here are four ways to use this function.

Use traditional anonymous inner classes, which can only be done before java8

List singularList = filter (targetList, new Predicate () {@ Override public boolean test (Integer integer) {return integer% 2! = 0;}}); System.out.println (singularList)

The lambda expression format is as follows: ()-> {}, () is the method list,-> {} is the method body, because there is only one parameter, and the parameter type can be inferred, so the type and () can not be written, the method body has only one sentence, {} can not be written, it is not recommended to write too long code in the method body, should ensure readability

List singularList2 = filter (targetList, integer-> integer% 2! = 0); / / the following is the complete writing / / List singularList3 = filter (targetList, (Integer integer)-> {/ / return integer% 2! = 0; / /})

For reasons that can be used, lambda expressions satisfy the abstract operation that a boolean is returned by the input Integer, which can be automatically converted into a function interface.

Static method reference, where a static method is defined, which can also be automatically converted to a function interface, using double colon syntax

Private static boolean integerWithSingular (Integer ) {return % 2! = 0;}

Using static method references, where Cn is the name of the class, can further improve readability compared to lambda expressions, because the method has a name, you can determine what you are doing by name, and it is more suitable for writing more logic

List singularList3 = filter (targetList, Cn::integerWithSingular)

Instance method, because the first parameter of any instance method is always a hidden pointer this to the current instance. Since the generics in the above example pass in the Integer type, you need to rewrite the expectation before you can demonstrate. Declare a class first, and there is an instance method that completes the mapping of boolean returned by the passed Test type.

Public class Test {private long id; public Test (long id) {this.id = id;} private boolean integerWithSingular () {return this.id% 2! = 0;}}

Replace all the Integer types of filter functions with Test types

Public static List filter (List list, Predicate predicate) {List result = new ArrayList (); for (Test item: list) {if (predicate.test (item)) {result.add (item);}} return result;}

In the following call, pass in the class name:: the effect of the instance method name is equivalent

ArrayList targetList = new ArrayList () {{this.add (new Test (1)); this.add (new Test (2));}}; filter (targetList,Test::integerWithSingular)

Any interface that contains only one abstract method can be automatically converted into a function interface, and the self-defined interface can be annotated without the @ FunctionalInterface tag.

A more frequently used function interface

Consumer inputs an object, and the output is empty, which is equivalent to consuming the incoming object. ArrayList's forEach method uses Consumer

/ / the forEach method source code of ArrayList @ Override public void forEach (Consumer

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report