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

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.
主站蜘蛛池模板: 定南县| 斗六市| 北海市| 齐齐哈尔市| 根河市| 桓台县| 开阳县| 城固县| 崇信县| 涡阳县| 枝江市| 石泉县| 温泉县| 景东| 宿松县| 浦东新区| 阜阳市| 东光县| 齐河县| 建阳市| 融水| 越西县| 上犹县| 花莲市| 岑溪市| 福鼎市| 鄂尔多斯市| 深州市| 南华县| 章丘市| 尉犁县| 新泰市| 永德县| 延寿县| 定安县| 西盟| 桦南县| 丰顺县| 海兴县| 嵊州市| 环江|