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

How to use Lambda expression and function programming in Java

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

Share

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

This article focuses on "how to use Lambda expressions and function programming in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Lambda expressions and functions in Java.

Catalogue

1. Brief introduction

2. Lambdas and Scopes

3. Lambdas and local variables

4. Lambda body and local variables

5. Lambdas and 'This' and' Super' keywords

6. Lambdas and Exceptions

7. Predefined functional interfaces

1. Brief introduction

The first example demonstrates lambda in the context of a variable declaration. It assigns lambda ()-> {System.out.println ("running");} to the variable r of the runnable interface type.

The second example is similar, but demonstrates lambda in the context of an assignment (to the previously declared variable r).

The third example demonstrates lambda in the context of a return statement. It calls the getFilter () method with the specified file extension parameter to return the java.io.FileFilter object. This object is passed to the listFiles () method of java.io.File, which invokes the filter for each file, ignoring files that do not match the extension. The getFilter () method returns the FileFilter object represented by lambda. The compiler notes that lambda satisfies the boolean accept (file path name) method of this function interface (both have a parameter, and the lambda body returns a Boolean value) and binds lambda to FileFilter.

The fourth example demonstrates the use of lambda in the context of an array initializer. Two java.nio.file.PathMatcher objects are created based on lambdas. Each PathMatcher object matches the file according to the criteria specified by its lambda principal. The following is the relevant code:

Final PathMatcher matchers [] = {(path)-> path.toString () .endsWith ("txt"), (path)-> path.toString () .endsWith ("java")}

The PathMatcher function interface provides a boolean matches (Path path) method that is consistent with the parameter list of lambda and the Boolean return type of its body. This method is then called to determine the match (based on the file extension) for each file encountered during access to the current directory and subdirectories.

The fifth example demonstrates lambda in the context of a thread constructor.

The sixth example demonstrates lambda in the context of lambda, which shows that lambda can be nested.

The seventh example demonstrates the ternary conditional expression (? Lambda in context: selects one of the two lambda based on ascending or descending order.

The eighth (and final) example demonstrates lambda in the context of a cast expression. ()-> System.getProperty ("user.name") lambda is cast to the PrivilegedAction function interface type. This cast resolves ambiguity in the java.security.AccessController class, which declares the following methods:

Static T doPrivileged (PrivilegedAction action) static T doPrivileged (PrivilegedExceptionAction action)

The problem is that each interface of PrivilegedAction and PrivilegedExceptionAction declares the same T run () method. Because the compiler cannot determine which interface is the target type, an error is reported without a cast.

Compile listing 4 and run the application. You should observe the following output, which assumes that LambdaDemo.java is the only .java file in the current directory and that the directory does not contain .txt files:

RunningrunningFound matched file:'.\ LambdaDemo.java'.runningcalledWashingtonSydneyRomeOttawaMoscowLondonJerusalemBerlinjeffrey2, Lambdas and Scopes

The term scope refers to the part of a program whose name is bound to a specific entity, such as a variable. In another part of the program, the name may be bound to another entity. Lambda principals do not introduce new scopes. Instead, its scope is closed.

3. Lambdas and local variables

The lambda body can define local variables. Because these variables are considered to be part of a closed scope, the compiler reports an error when it detects that the lambda body is redefining local variables. Listing 5 illustrates this problem.

Listing 5. LambdaDemo.java (version 5)

Public class LambdaDemo {public static void main (String [] args) {int limit = 10; Runnable r = ()-> {int limit = 5; for (int I = 0; I)

< limit; i++) System.out.println(i); }; }} 因为limit已经存在于封闭范围(main()方法)中,lambda主体对limit的重新定义(int limit=5;)会导致编译器报告以下错误消息:错误:变量limit已经在方法main(字符串[])中定义。 4、Lambda体与局部变量 无论是源于lambda主体还是在封闭范围内,局部变量在使用之前都必须初始化。否则,编译器将报告错误。 在lambda主体外部定义并从主体引用的局部变量或参数必须标记为final或视为有效final(初始化后无法将该变量指定给)。试图修改一个有效的最终变量会导致编译器报告一个错误,如清单6所示。 清单6。LambdaDemo.java(版本6) public class LambdaDemo{ public static void main(String[] args) { int limit = 10; Runnable r = () ->

{limit = 5; for (int I = 0; I

< limit; i++) System.out.println(i); }; }} 限制实际上是最终的。lambda主体试图修改此变量会导致编译器报告错误。这样做是因为final/final变量需要挂起,直到lambda执行为止,这可能要在定义变量的代码返回后很久才会发生。非最终/非有效最终变量不再存在。 5、Lambdas和'This'和'Super'关键字 lambda主体中使用的任何this或super引用都被视为等同于其在封闭范围中的用法(因为lambda不引入新范围)。然而,匿名类的情况并非如此,如清单7所示。 清单7。LambdaDemo.java(版本7) public class LambdaDemo{ public static void main(String[] args) { new LambdaDemo().doWork(); } public void doWork() { System.out.printf("this = %s%n", this); Runnable r = new Runnable() { @Override public void run() { System.out.printf("this = %s%n", this); } }; new Thread(r).start(); new Thread(() ->

System.out.printf ("this =% s% n", this). Start ();}}

The main () method in listing 7 instantiates LambdaDemo and calls the object's doWork () method to output the this reference of the object, instantiates an anonymous class that implements Runnable, creates a thread object, executes this Runnable when its thread starts, and creates another thread object whose thread executes lambda at startup.

Compile listing 7 and run the application. You should observe something similar to the following output:

This = LambdaDemo@776ec8dfthis = LambdaDemo$1@48766bbthis = LambdaDemo@776ec8df

The first line shows the this reference for LambdaDemo, the second line shows the different this references in the new runnable scope, and the third line shows the this reference in the lambda context. The third line matches the first line because the scope of the lambda is nested in the doWork () method; this has the same meaning throughout the method.

6. Lambdas and Exceptions

The lambda body is not allowed to throw more exceptions than specified in the throws clause of the function interface method. If the lambda body throws an exception, the throws clause of the function interface method must declare the same exception type or its supertype. Consider listing 8.

Listing 8. LambdaDemo.java (version 8)

Import java.awt.AWTException;import java.io.IOException;@FunctionalInterfaceinterface Work {void doSomething () throws IOException;} public class LambdaDemo {public static void main (String [] args) throws AWTException, IOException {Work work = ()-> {throw new IOException ();}; work.doSomething (); work = ()-> {throw new AWTException (");};}}

Listing 8 declares a working function interface whose doSomething () method is declared to throw java.io.IOException. The main () method assigns the lambda that throws IOException to work, which is normal because IOException is listed in the throws clause of doSomething ().

Main () then allocates a lambda, which throws a java.awt.AWTException to work. However, the compiler does not allow this assignment because AWTException is not part of the throws clause of doSomething () (and certainly not a subtype of IOException).

7. Predefined functional interfaces

You may find yourself repeatedly creating similar functional interfaces. For example, you can create a CheckConnection function interface using the Boolean IsConnection (connection c) method and a CheckAccount function interface using the Boolean isPositiveBalance (account account) method. It's a waste.

The previous example exposes the abstract concept of predicates (Boolean-valued functions). Oracle provides java.util.function packages of common functional interfaces to predict these patterns. For example, the Predicate functional interface of this package can be used instead of CheckConnection and CheckAccount.

Predicate provides a boolean test (T t) method that evaluates the predicate based on its argument (t) and returns true if T matches predicate, or false otherwise. Note that test () provides the same list of parameters as isConnected () and isPositiveBalance (). Also, note that they all have the same return type (Boolean).

The application source code in listing 9 demonstrates the predicate.

Listing 9. LambdaDemo.java (version 9)

Import java.util.ArrayList;import java.util.List;import java.util.function.Predicate;class Account {private int id, balance; Account (int id, int balance) {this.balance = balance; this.id = id;} int getBalance () {return balance;} int getID () {return id } void print () {System.out.printf ("Account: [% d], Balance: [% d]% n", id, balance);}} public class LambdaDemo {static List accounts; public static void main (String [] args) {accounts = new ArrayList (); accounts.add (new Account (1000)); accounts.add (new Account (2000,-2000); accounts.add (new Account (3000, 0)) Accounts.add (new Account (4000,-80); accounts.add (new Account (5000, 1000)); / / Print all accounts printAccounts (account-> true); System.out.println (); / / Print all accounts with negative balances. PrintAccounts (account-> account.getBalance ()

< 0); System.out.println(); // Print all accounts whose id is greater than 2000 and less than 5000. printAccounts(account ->

Account.getID () > 2000 & & account.getID ()

< 5000); } static void printAccounts(Predicate tester) { for (Account account: accounts) if (tester.test(account)) account.print(); }} 清单9创建了一个基于数组的帐户列表,其中有正余额、零余额和负余额。然后,它通过使用lambdas调用printAccounts()来演示谓词,以便打印出所有帐户,仅打印出那些余额为负数的帐户,以及仅打印出ID大于2000且小于5000的帐户。 考虑lambda表达式帐户->

Really. The compiler verifies that the lambda matches the Boolean test (T) method of the predicate, and it does so-- lambda provides a single parameter (account), whose body always returns a Boolean value (true). For this lambda,test () is implemented to execute return true;.

Compile listing 9 and run the application. We can observe the following output:

Account: [1000], Balance: [2000] Account: [2000], Balance: [3000], Balance: [0] Account: [4000], Balance: [- 80] Account: [5000], Balance: [1000] Account: [2000], Balance: [2000] Account: [4000], Balance: [- 80] Account: [3000], Balance: [0] Account: [4000], Balance: [- 80]

Predicate is just one of the various predefined function interfaces for java.util.function. Another example is Consumer, which represents an operation that accepts a single parameter but does not return a result. Unlike Predicate, Consumer is expected to operate through side effects. In other words, it modifies its argument in some way.

The user's void accept (T) method performs an operation on its argument (T). When present in the context of this function interface, the lambda must conform to the individual parameters and return type of the accept () method.

At this point, I believe you have a deeper understanding of "how to use Lambda expression and function programming in Java". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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