Java 8 - lambda

0
0
0
1. 云栖社区>
2. 博客>
3. 正文

## Java 8 - lambda

pzwdshxzt 2018-01-31 15:30:11 浏览695

# lambda

## lambda主要的表示形式

(params) -> expression
(params) -> statement
(params) -> { statements }

Example
（） - > System.out.println(” Lambda Expressions”);
(int i, int j) -> System.out.println(i+j);

### Example No.1

`````` List features = Arrays.asList("Lambdas", "Method", "Java", "Hello");
features.forEach(n -> System.out.println(n));
// 使用Java 8的方法引用更方便，方法引用由::双冒号操作符标示，
features.forEach(System.out::println);``````

### Example No.2

`````` List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("Highest prime number in List : " + stats.getMax());
System.out.println("Lowest prime number in List : " + stats.getMin());
System.out.println("Sum of all prime numbers : " + stats.getSum());
System.out.println("Average of all prime numbers : " + stats.getAverage());``````

Highest prime number in List : 29
Lowest prime number in List : 2
Sum of all prime numbers : 129
Average of all prime numbers : 12.9

### Example No.3

map - reduce 例子

``````List<Integer> costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);
//这个是将每个数都变成浮点数 * 12
costBeforeTax.stream().map((cost) -> cost + .12 * cost ).forEach(System.out::println);
//这个是将每个数都变成浮点数 * 12 然后再算和
double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();
System.out.println("Total : " + bill);``````

112.0
224.0
336.0
448.0
560.0
Total : 1680.0

``````map---对列表的每个元素应用函数使用
// 将字符串换成大写并用逗号链接起来
List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany", "Italy", "U.K.","Canada");
String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(", "));
System.out.println(G7Countries);``````

### Example No.4

``````// Java 8之前：
@Override
public void run() {
System.out.println("Rock it!");
System.out.println("Hello world");
}
}).start();
//java8 支持
System.out.println("Rock it!");
System.out.println("hello world!");
}).start();``````

Rock it!
Hello world!

### Example No.5

Java 8也添加了一个包，叫做 java.util.function。它包含了很多类，用来支持Java的函数式编程。其中一个便是Predicate，使用 java.util.function.Predicate 函数式接口以及lambda表达式，可以向API方法添加逻辑，用更少的代码支持更多的动态行为。下面是Java 8 Predicate 的例子，展示了过滤集合数据的多种常用方法。Predicate接口非常适用于做过滤。

``````// 甚至可以用and()、or()和xor()逻辑函数来合并Predicate，
// 例如要找到所有以J开始，长度为四个字母的名字，你可以合并两个Predicate并传入
List<String> languages = Arrays.asList("Java", "Scala", "C++", "Haskell", "Lisp","h","d","map","r");
Predicate<String> startsWithJ = (n) -> n.startsWith("J");
Predicate<String> fourLetterLong = (n) -> n.length() == 4;
languages.stream()
.filter(startsWithJ.and(fourLetterLong))
.forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));``````

Original List : [Java, Scala, C++, Haskell, Lisp, h, d, map, r], filtered list : [Java, Scala, C++, Haskell, Lisp, map]

pzwdshxzt
+ 关注