当前位置: 首页 > 工具软件 > Lam > 使用案例 >

jdk8新特性之lam表达式的4个基本方法及::运算符

斜光耀
2023-12-01
package com.boot.demo;

import org.junit.jupiter.api.Test;

import java.util.function.*;

public class LambdaTest {

    @Test
    private void test(){
        Runnable runnable = System.out::println;   //相当于一个无参无返回值的方法
        Runnable runnable1 = () -> System.out.println();
        Runnable runnable2 = () -> {
            System.out.println();
        };
        Runnable runnable3 = new Runnable() {
            @Override
            public void run() {
                System.out.println();
            }
        };

        Consumer c = System.out::println;      //相当于一个有参的void方法
        Consumer c1 = x -> System.out.println(x);
        Consumer c2 = x -> {
            System.out.println(x);
        };
        Consumer c3 = new Consumer() {
            @Override
            public void accept(Object x) {
                System.out.println(x);
            }
        };

        Supplier s = () -> {return 123;};       //相当于一个无参有返回值的方法
        Supplier s1 = new Supplier() {
            @Override
            public Object get() {
                return 123;
            }
        };
        Supplier s2 = LambaTest::get;

        Function<Integer,Integer> f = x -> {return  x+2;};   //相当于一个有参有返回值的方法
        Function<Integer,Integer> f1 = new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer x) {
                return x + 2;
            }
        };
        Function<Integer,Integer> f2 = LambaTest::apply;

    }

    private static Object get() {
        return 123;
    }
    private static Integer apply(Integer x) {
        return x + 2;
    }
}

 

 类似资料: