专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

java8:lambda表达式

1、lambda表达式的书写

(1)lambda表达式:在java中Lambda表达式是对象,他们必须依赖于一类特别的对象类型函数式接口

@FunctionalInterface
interface MyInterface1{
    void myMethod1();
}

@FunctionalInterface
interface MyInterface2{
    void myMethod2();
}

public class Test1 {
    public static void main(String[] args) {
        MyInterface1 interface1=()->{};
        System.out.println(interface1.getClass().getInterfaces()[0]);

        MyInterface2 interface2=()->{};
        System.out.println(interface2.getClass().getInterfaces()[0]);
    }
}
表达式的书写一定要根据上下文信息(两个函数式接口):
例如:
interface MyInterface2{
    void myMethod2();
}

接口是无参数的,那么lambda表达式的小括号代表参数内容(这里为空),{ },代表的是接口中的内容(这里面的函数式接口不接收参数,不返回值,():方法的参数,{}:方法的实现),函数式接口是直接找的抽象方法。

2、Runable接口

(1)它是一个函数式接口,因为该接口只有一个抽象方法:

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

(2)创建一个线程:

普通方式:

new Thread(new Runnable() {
            @Override
            public void run() {

            }
        }).start();

lambda表达式:

new Thread(()->System.out.println("ni hao")).start();

3、应用

(1) 小写转换为大写:

  public static void main(String[] args) {
        List<String> list= Arrays.asList("jia","you");
        list.forEach(item->System.out.println(item.toUpperCase()));
    }
JIA
YOU

(2)小写转大写后,在存储到一个新的集合中:

    public static void main(String[] args) {
        List<String> list= Arrays.asList("jia","you");
        List<String> list1=new ArrayList<>();
        list.forEach(item->list1.add(item.toUpperCase()));
        list1.forEach(item->System.out.println(item));
    }

转化为流后处理:

    public static void main(String[] args) {
        List<String> list= Arrays.asList("jia","you");
        list.stream().map(item->item.toUpperCase()).forEach(item->System.out.println(item));
    }

方法的引用方式实现:

   public static void main(String[] args) {
        List<String> list= Arrays.asList("jia","you");
        list.stream().map(String::toUpperCase).forEach(item->System.out.println(item));
    }

文章永久链接:https://tech.souyunku.com/22602

未经允许不得转载:搜云库技术团队 » java8:lambda表达式

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们