亲宝软件园·资讯

展开

JAVA8学习——深入浅出Lambda表达式(学习过程)

dawa大娃bigbaby 人气:1

JAVA8学习——深入浅出Lambda表达式(学习过程)

lambda表达式:

我们为什么要用lambda表达式

  • 在JAVA中,我们无法将函数作为参数传递给一个方法,也无法声明返回一个函数的方法。
  • 在JavaScript中,函数参数是一个函数,返回值是另一个函数的情况下非常常见的,JavaScript是一门非常典型的函数式编程语言,面向对象的语言
//如,JS中的函数作为参数
a.execute(callback(event){
    event...
})

Java匿名内部类实例

后面补充一个匿名内部类的代码实例

我这里Gradle的使用来构建项目

需要自行补充对Gradle的学习

Gradle完全可以使用Maven的所有能力
Maven基于XML的配置文件,Gradle是基于编程式配置.Gradle文件

自定义匿名内部类

public class SwingTest {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame("my Frame");
        JButton jButton = new JButton("My Button");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Button Pressed");
            }
        });
        jFrame.add(jButton);
        jFrame.pack();
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

改造前:

jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                System.out.println("Button Pressed");
            }
        });

改造后:

jButton.addActionListener(actionEvent -> System.out.println("Button Pressed"));

Lambda表达式的基本结构

会有自动推断参数类型的功能

(pram1,pram2,pram3)->{
    
}

函数式接口

概念后期补(接口文档源码,注解源码)
抽象方法,抽象接口
1个接口里面只有一个抽象方法,可以有几个具体的方法

/**
 * An informative annotation type used to indicate that an interface
 * type declaration is intended to be a <i>functional interface</i> as
 * defined by the Java Language Specification.
 *
 * Conceptually, a functional interface has exactly one abstract
 * method.  Since {@linkplain java.lang.reflect.Method#isDefault()
 * default methods} have an implementation, they are not abstract.  If
 * an interface declares an abstract method overriding one of the
 * public methods of {@code java.lang.Object}, that also does
 * <em>not</em> count toward the interface's abstract method count
 * since any implementation of the interface will have an
 * implementation from {@code java.lang.Object} or elsewhere.
 *
 * <p>Note that instances of functional interfaces can be created with
 * lambda expressions, method references, or constructor references.
 *
 * <p>If a type is annotated with this annotation type, compilers are
 * required to generate an error message unless:
 *
 * <ul>
 * <li> The type is an interface type and not an annotation type, enum, or class.
 * <li> The annotated type satisfies the requirements of a functional interface.
 * </ul>
 *
 * <p>However, the compiler will treat any interface meeting the
 * definition of a functional interface as a functional interface
 * regardless of whether or not a {@code FunctionalInterface}
 * annotation is present on the interface declaration.
 * 
 * @jls 4.3.2. The Class Object
 * @jls 9.8 Functional Interfaces
 * @jls 9.4.3 Interface Method Body
 * @since 1.8
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}


关于函数式接口:
1.如何一个接口只有一个抽象方法,那么这个接口就是函数式接口
2.如果我们在某个接口上生命了FunctionalInterface注解,那么编译器就会按照函数式接口的定义来要求该注解
3.如果某个接口只有一个抽象方法,但我们没有给该接口生命FunctionalInterface接口,编译器也还会把该接口当做成一个函数是接口。(英文最后一段)

通过对实例对函数式接口深入理解

对
@FunctionalInterface
public interface MyInterface {
    void test();
}

错
@FunctionalInterface
public interface MyInterface {
    void test();

    String tostring1();
}

对 (tostring为重写Object类的方法)
@FunctionalInterface
public interface MyInterface {
    void test();

    String toString();
}

升级扩展,使用lambda表达式

@FunctionalInterface
interface MyInterface {
    void test();

    String toString();
}

public class Test2{
    public void myTest(MyInterface myInterface){
        System.out.println("1");
        myInterface.test();
        System.out.println("2");
    }

    public static void main(String[] args) {
        Test2 test2 = new Test2();
        //1.默认调用接口里面的接口函数。默认调用MyTest接口里面的test方法。
        //2.如果没有参数传入方法,那么可以直接使用()来表达,如下所示
        test2.myTest(()-> System.out.println("mytest"));
        
        MyInterface myInterface = () -> {
            System.out.println("hello");
        };

        System.out.println(myInterface.getClass()); //查看这个类
        System.out.println(myInterface.getClass().getSuperclass());//查看类的父类
        System.out.println(myInterface.getClass().getInterfaces()[0]);// 查看此类实现的接口
    }
}

默认方法:接口里面,从1.8开始,也可以拥有方法实现了。

默认方法既保证了新特性的添加,又保证了老版本的兼容

//如,Iterable 中的 forEach方法
public interface Iterable<T> {
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
}

ForEach方法详解

比较重要的是行为,//action行为,而不是数据


/**
     * Performs the given action for each element of the {@code Iterable}
     * until all elements have been processed or the action throws an
     * exception.  Unless otherwise specified by the implementing class,
     * actions are performed in the order of iteration (if an iteration order
     * is specified).  Exceptions thrown by the action are relayed to the
     * caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     for (T t : this)
     *         action.accept(t);
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

Consumer 类型详解

名字的由来:消费,只消费,没有返回值

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.//接口本身是带有副作用的,会对传入的唯一参数进行修改
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Lambda表达式的作用

  • Lambda表达式为JAVA添加了缺失的函数式编程特性,使我们能够将函数当做一等公民看待
  • 在将函数作为一等公民的语言中,Lambda表达式的类型是函数,但是在JAVA语言中,lambda表达式是一个对象,他们必须依附于一类特别的对象类型——函数是接口(function interface)

迭代方式(三种)

外部迭代:(之前使用的迭代集合的方式,fori这种的)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

内部迭代: ForEach(完全通过集合的本身,通过函数式接口拿出来使用Customer的Accept来完成内部迭代)

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

第三种方式:方法引用(method reference)

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

2019年12月29日00:07:05 要睡觉了。笔记后面持续更新,代码会上传到GitHub,欢迎一起学习讨论。

加载全部内容

相关教程
猜你喜欢
用户评论