简体   繁体   English

在Lambda Expressions(Java)中,如何使用没有参数的表达式?

[英]In Lambda Expressions (Java), how is an expression without parameter used?

As I know, there are 3 kinds of java lambda expressions. 据我所知,有3种java lambda表达式。

  1. (int x, int y) -> { return x + y; }
  2. x -> x * x
  3. ( ) -> x

The third one seems never ever used. 第三个似乎从未使用过。

Could you give an example for each of the 3 cases (an extra example for case 3 will be good) to illustrate their usage? 你能举一个例子来说明3个案例中的每个案例(案例3的另一个例子是好的)来说明它们的用法吗? Please make them as simple as possible (preferably starting with list.stream()....) 请使它们尽可能简单(最好从list.stream()....开始)

  1. The first expression will be used where you get 2 parameters for a method and return a value. 第一个表达式将用于获取方法的2个参数并返回值的位置。

  2. The second expression will be used x -> x * x where you get 1 parameters for a method and return a value. 第二个表达式将使用x -> x * x ,其中您获得方法的1个参数并返回值。

  3. The third expression ( ) -> x will be used ( ) -> x where you get 0 parameters for a method and return a value. 第三个表达式( ) -> x将用于( ) -> x ,其中您获得方法的0个参数并返回一个值。

Let's take the third one. 我们来看第三个。 Suppose you have an interface which takes no parameters and returns a value. 假设您有一个不带参数的接口并返回一个值。

static interface RandomMath {
    public int random();
}

Now You want to instantiate this interface along with its implementation. 现在您想要实例化此接口及其实现。 Without using lambda it will be done as below:- 不使用lambda,将按如下方式完成: -

Random random = new Random();
RandomMath randomMath = new RandomMath() {
    @Override
    public int random() {
        return random.nextInt();
    }
};

Using lambda it will be like:- 使用lambda就像: -

Random random = new Random();
RandomMath randomMath = () -> random.nextInt(); //the third type.

Similarly, for first two it can be used for methods which take two and one parameters and return a value. 类似地,对于前两个,它可以用于采用两个和一个参数并返回值的方法。

static interface PlusMath {
    public int plus(int a, int b);
}

PlusMath plusMath = (a, b) -> a + b;

static interface SquareMath {
    public int square(int a);
}

SquareMath squareMath = a -> a * a;

The first two examples are different from the last one. 前两个例子与上一个例子不同。 The variables in the function (lambda expression) refer to its parameters. 函数中的变量(lambda表达式)指的是其参数。

While in the third example the x refers to variable outside of the lambda expression but within the lexical scope (can be either local variable from the method or instance variable). 而在第三个示例中, x指的是lambda表达式之外但在词法范围内的变量(可以是方法或实例变量中的局部变量)。

Example 1 (typically stream reduce), computes the sum by passing the so far computed sum and next item from the list to lambda function: 示例1(通常是stream reduce)通过将列表中到目前为止计算的sum和next项传递给lambda函数来计算总和:

 int sum = list.stream().reduce((int x, int y) -> x+y);

Example 2, computes the squares from the elements: 例2,计算元素的方块:

 squares = list.stream().map((int x) -> x*x).collect(Collectors.toList());

Example 3, sets the element to default value if it's null in the list: 示例3,如果元素在列表中为null,则将元素设置为默认值:

 final int x = MY_DEFAULT_VALUE;
 // lambda refers the the variable above to get the default
 defaults = list.stream().map((Integer v) -> v != null ? v : x);

Or better for example 3 is the map atomic methods: 或者更好的例如3是地图原子方法:

 int x = MY_DEFAULT_VALUE;
 // lambda refers the the variable above to get the default
 map.computeIfAbsent(1, (Integer key) -> x);
 // the same could be achieved by putIfAbsent() of course
 // but typically you would use (Integer key) -> expensiveComputeOfValue(x)
 // ...
 // or quite common example with executor
 public Future<Integer> computeAsync(final int value) {
     // pass the callback which computes the result synchronously, to Executor.submit()
     // the callback refers to parameter "value"
     return executor.submit(() -> computeSync(value));
 }

Before going through the below examples, first, note that Lambda expressions can be written for any SAM (also called Functional) interfaces (Infact, Lambda expression is a syntactic sugar for replacing the verbose anonymous class (with single method) in Java). 在完成以下示例之前,请注意,可以为任何SAM(也称为Functional)接口编写Lambda表达式 (Infact, Lambda表达式是用于替换Java中的详细匿名类(使用单个方法) 的语法糖 )。

Single Abstract Method interface or Functional Interface is an interface which contains only one abstract method), you can look here . 单个抽象方法接口或功能接口是一个只包含一个abstract方法的接口,您可以在此处查看 If you know this simple point, you can write (play with) any number of your own Functional interfaces and then write the different Lambda Expressions according to each of those the Functional interface methods. 如果您知道这一点,您可以编写(使用)任意数量的自己的Functional接口,然后根据每个Functional接口方法编写不同的Lambda表达式。

Below examples have been written by making use of the existing JDK (1.8) Functional interfaces like Callable , Function , BiFunction (Like these, there are many in built Functional interfaces in JDK 1.8, most of the times they readily suit our requirements ). 下面的示例是通过使用现有的JDK(1.8)功能接口(如CallableFunctionBiFunction (就像这些, 在JDK 1.8中有许多内置的功能接口,大多数时候它们很容易满足我们的要求 )。

(1) Example for (int x, int y) -> { return x + y; (1)(int x,int y) - > {return x + y; } }

//Below Lamda exp, takes 2 Input int Arguments and returns string
BiFunction<Integer, Integer, String> biFunction = (num1, num2) -> 
               "Sum Is:" +(num1 + num2);
System.out.println(biFunction.apply(100, 200));

(2) Example for x -> x * x (2)x - > x * x的例子

//Below Lamda exp, takes string Input Argument and returns string
list.stream().map((String str1) -> 
       str1.substring(0, 1)). 
           forEach(System.out::println);    

(3) Example for () -> x (3)() - > x的例子

//Below Lambda exp, Input argument is void, returns String
Callable<String> callabl = () -> "My Callable";
ExecutorService service =  Executors.newSingleThreadExecutor();
Future<String> future = service.submit(callable);
System.out.println(future.get());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM