Lambda表达式及双冒号操作符

一、Lambda表达式基本语法

(parameters) -> expression

(parameters) ->{ statements; }

// 不需要参数,返回值为6
() -> 5

// 参数x,返回值为6*x
(x) -> 6*x

// 参数x和y,返回值为x*y
(x, y) -> x*y

// 参数s, 打印输出
(String s) -> System.out.print(s) 

二、常用场景

列表迭代:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
list.forEach(x -> System.out.println(x));

线程声明启动:

Runnable run = ()->{
  for (int j = 0; j < 10; j++) {
      System.out.println(name + " " + j);
  }
};
new Thread(run).start();

三、双冒号操作符

双冒号操作符实际是Lambda表达式的一种简写。

x -> System.out.println(x)      等价于   System.out::println

发布了92 篇原创文章 · 获赞 3 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41231928/article/details/103375309