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

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.
主站蜘蛛池模板: 鹤庆县| 台北县| 固原市| 清镇市| 罗甸县| 山东| 甘肃省| 冕宁县| 婺源县| 乌拉特中旗| 武鸣县| 新安县| 伊春市| 蒲城县| 安乡县| 焦作市| 浪卡子县| 三门峡市| 泊头市| 平塘县| 勃利县| 南部县| 辉南县| 开封县| 江安县| 南开区| 依兰县| 城口县| 清原| 休宁县| 上饶市| 南部县| 那曲县| 观塘区| 武邑县| 昔阳县| 凤台县| 霍林郭勒市| 淅川县| 九江县| 宁城县|