Lambda Expression Introduction

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/12806947.html

 

Definition

A lambda expression can be understood as a concise representation of an anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown. That’s one big definition;

let’s break it down:

  • Anonymous— We say anonymous because it doesn’t have an explicit name like a method would normally have: less to write and think about!
  • Function— We say function because a lambda isn’t associated with a particular class like a method is.But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown.
  • Passed around— A lambda expression can be passed as argument to a method or stored in a variable.
  • Concise— You don’t need to write a lot of boilerplate like you do for anonymous classes.

 

Demo

ThreadTest.java

 1 package org.fool.java8;
 2 
 3 public class ThreadTest {
 4     public static void main(String[] args) {
 5         new Thread(new Runnable() {
 6             @Override
 7             public void run() {
 8                 System.out.println(Thread.currentThread().getName());
 9             }
10         }).start();
11 
12         new Thread(() -> {
13             System.out.println(Thread.currentThread().getName());
14         }).start();
15 
16         new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
17     }
18 }

 

Reference

Manning.Java.8.in.Action.Lambdas.Streams.and.functional-style.programming.Aug.2014

 

posted @ 2020-04-30 09:47  李白与酒  阅读(173)  评论(0编辑  收藏  举报