java8新特性之lambda表达式

Lambda 表达式实例

Lambda 表达式的简单例子:

// 1. 不需要参数,返回值为 5 

() -> 5 

// 2. 接收一个参数(数字类型),返回其2倍的值 

x -> 2 * x 

// 3. 接受2个参数(数字),并返回他们的差值 

(x, y) -> x – y 

// 4. 接收2个int型整数,返回他们的和 

(int x, int y) -> x + y 

// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void) 

(String s) -> System.out.print(s)

代码实现实例:

package com.jump.test;

import java.util.ArrayList;

import java.util.List;

/**

* Created by Administrator on 2020/1/9.

*/

public class lambdatest {

public static void main(String[] args) {

ITest it = param -> System.out.println("hello lambda "+param);

        it.s1("haha");

        List list =new ArrayList<>();

        list.add("pppooooo1");

        list.add("pppooooo2");

        list.add("pppooooo3");

        list.add("pppooooo4");

        //

        list.forEach(pam -> {int p =99;System.out.print(pam);

            System.out.println(p);

        new Thread(()-> System.out.println(Thread.currentThread().getName()),

                "lambda_"+(int)(Math.random()*10)).start();});

        //

        ITest2 it2 = ()->3;

        System.out.println(it2.s1());

        //

        ITest3 it3 = (a,b)-> a+b;

        System.out.println(it3.t1(44,55));

    }

interface ITest3{

int t1(int a,int b);

    }

interface ITest2{

int s1();

    }

interface ITest{

void s1(String param);

    }

}

你可能感兴趣的:(java8新特性之lambda表达式)