官术网_书友最值得收藏!

Syntax of Lambda expressions

A Lambda expression consists of two parts: 0 or more arguments and the function body:

argument -> function 
(argument1,argument2,...argument) -> function 

Let's discuss it with examples. Consider a list of integers as follows:

List<Integer> list = Arrays.asList(1,2,3,4,5);

Print each element of the list using Lambda:

list.forEach(n-> System.out.println(n));

Multiply each element of the list by 2:

list.stream().map(n -> n*2 );
The stream method will convert the list to a stream of numbers. We will discuss more about it in another section. For now, just consider that the stream will convert all the elements of the list into the stream.

Here, we do not need to specify the type of n. The type of n is auto-inferred in Lambda. Also, we have not specified any return statement. The return statement is implicit in Lambda. If you want, you can specify the return statement explicitly as follows:

list.stream().map(n -> { 
      return n*2; 
   }); 
}  
For specifying the return type explicitly, you need to enclose the function body in braces and provide a semicolon ( ;) at the end of the return statement.
主站蜘蛛池模板: 永登县| 隆林| 嘉禾县| 西和县| 如皋市| 正安县| 会同县| 乡城县| 衡阳市| 余干县| 九龙坡区| 西宁市| 柏乡县| 乌兰察布市| 南康市| 文登市| 浠水县| 南召县| 浦东新区| 黑龙江省| 磐石市| 江陵县| 绍兴县| 前郭尔| 宜丰县| 宣恩县| 孟州市| 朝阳市| 邮箱| 鄂托克旗| 高尔夫| 汶上县| 东城区| 财经| 枣庄市| 涞水县| 安塞县| 乌拉特中旗| 施甸县| 正蓝旗| 普宁市|