Home >Java >javaTutorial >How to use Lambda expression to access external variables in Java?

How to use Lambda expression to access external variables in Java?

WBOY
WBOYforward
2023-04-25 18:04:081824browse

1. You can access external final type variables in Lambda expressions.

// 转换器
@FunctionalInterface
interface Converter<F, T> {
    T convert(F from);
}

2. Unlike anonymous inner classes, there is no need to explicitly declare the num variable as final type.

int num = 1;
Converter<Integer, String> stringConverter =
        (from) -> String.valueOf(from + num);
 
stringConverter.convert(2);     // 3

What are the advantages of Java

1. Simple. As long as you understand the basic concepts, you can write applications suitable for various situations;

2. Object-oriented;

3. Distribution, Java is a network-oriented language;

4. Robustness, Java provides automatic garbage collection for memory management, preventing programs from Errors that are easy for operators to make when managing memory;

5. Security, Java used in network and distributed environments must prevent virus intrusion;

6. Architecture neutrality, as long as it is installed With the Java runtime system, it can run on any processor;

7. Portability, Java can be easily transplanted to different machines on the network;

8. Interpretation and execution, The Java interpreter directly interprets and executes Java bytecode.

The above is the detailed content of How to use Lambda expression to access external variables in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete