java 8 - lambda表达式用法示例

  • 可以使用lambda表达式代替单抽象方法SAM,替代了匿名类的使用方式

// Java 8之前:

new Thread(new Runnable() {

@Override

public void run() {

System.out.println("Before Java8, too much code for too little to do");

}

}).start();

1

2

//Java 8方式:

new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();

  • 函数式接口Predicate,使用Predicate配置stream流

1

2

3

4

5

6

7

// 甚至可以用and()、or()和xor()逻辑函数来合并Predicate,

// 例如要找到所有以J开始,长度为四个字母的名字,你可以合并两个Predicate并传入

Predicate<String> startsWithJ = (n) -> n.startsWith("J");

Predicate<String> fourLetterLong = (n) -> n.length() == 4;

names.stream()

.filter(startsWithJ.and(fourLetterLong))

.forEach((n) -> System.out.print("nName, which starts with 'J' and four letter long is : " + n));

  • lambda表达式的Map和Reduce示例

1

2

3

4

5

6

7

8

9

10

11

12

13

14

// 为每个订单加上12%的税

// 老方法:

List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);

double total = 0;

for (Integer cost : costBeforeTax) {

double price = cost + .12*cost;

total = total + price;

}

System.out.println("Total : " + total);

// 新方法:

List costBeforeTax = Arrays.asList(100, 200, 300, 400, 500);

double bill = costBeforeTax.stream().map((cost) -> cost + .12*cost).reduce((sum, cost) -> sum + cost).get();

System.out.println("Total : " + bill);

  • 利用流的 distinct() 方法来对集合进行去重

1

2

3

4

// 用所有不同的数字创建一个正方形列表

List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);

List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

System.out.printf("Original List : %s,  Square Without duplicates : %s %n", numbers, distinct);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值