Java8-Lambda语法

admin
2022-09-05 / 0 评论 / 84 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年09月08日,已超过598天没有更新,若内容或图片失效,请留言反馈。

Lambda表达式

一、lambda语法

参数列表 lambda body部分

(o1,o2)->o1.getWeight().compareTo(o2.getWeight());

二、 合法lamdba表达式

1、s -> s.length(); 或者 (String s) -> s.length();

2、apple -> apple.getColor().equals("great"); 或者 (Apple apple) -> apple.getColor().equals("great");

3、(int x, int y) -> {

System.out.println(x);

System.out.println(y);

};

4、() -> 12;

5、()-{};

6、()->“hello” 或者 ()->{return "hello"}

三、语法总结

语法一、(参数列表) -> 表达式

语法二、(参数列表) -> {语句;}

有效lambda表达式

1、() -> {}

2、() -> "hello" 或者 ()->{reurn "hello"}

3、(String str) -> {return "hello"} 或者 (String str) -> "hello";

无效lambda表达式

(integer i)->{return "错误示范"+i}

四、代码说明

package com.example.study.java8.InterfaceFunction;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * lambda语法
 */
public class LambdaExpression {
    public static void main(String[] args) {
        Comparator<Apple> colorComparator = new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o1.getColor().compareTo(o2.getColor());
            }
        };

        List<Apple> apples = Arrays.asList(new Apple("a", 18), new Apple("c", 20), new Apple("b", 10));
        for (Apple a : apples) {
            System.out.println(a.toString());
        }

        System.out.println("=================================");


        apples.sort(colorComparator);

        for (Apple a : apples) {
            System.out.println(a.toString());
        }

        System.out.println("=================================");
        //lambda expression
        //方法推导:接口有返回值时,注意lambda有大括号{},必须要有return,没有可以不用使用return关键词
        //1、有{},必须使用return
        Comparator<Apple> weightComparator = (o1, o2) -> {
            return o1.getWeight().compareTo(o2.getWeight());
        };
        //2、不使用{},没有return
        Comparator<Apple> weightComparator2 = (o1, o2) -> o1.getWeight().compareTo(o2.getWeight());

        apples.sort(weightComparator);

        for (Apple a : apples) {
            System.out.println(a.toString());
        }

        //合法lambda表达式格式1
        Function<String, Integer> stringIntegerFunction = s -> s.length();

        //合法lambda表达式格式2
        Predicate<Apple> great = (Apple apple) -> apple.getColor().equals("great");
        Predicate<Apple> great2 = apple -> apple.getColor().equals("great");

        //合法lambda表达式格式3
//        (int x, int y) -> {
//            System.out.println(x);
//            System.out.println(y);
//        };

        //合法lambda表达式格式4
        Callable<Integer> integerCallable = () -> 12;

        //合法lambda表达式格式5
        Runnable runnable = () -> {

        };

        //合法lambda表达式格式6
        Callable<String> stringCallable = () -> "hello";

        //合法lambda表达式格式7
        Function<String, String> stringStringFunction = (String str) -> {
            return "hello";
        };

        //合法lambda表达式格式8
        Function<String, String> stringStringFunction1 = (String str) -> "hello";

    }

}

五、学习目标

熟悉lambda语法后,主要学习:function、stream。

java.util.function、java.util.stream包下接口用法

六、Function学习

java.util.function包下主要的4中lambda接口用法以及扩展用户

1、Function有返回值

@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

范例:

        //Funcation有返回参数类型
        //1、返回Boolean类型
        Function<Apple, Boolean> boolearnFunction = apple -> apple.getColor().equals("red");
        //2、返回String类型
        Function<Apple, String> stringFunction = apple -> apple.getColor();
        //3、返回Integer类型
        Function<Apple, Integer> integerFunction = apple -> apple.getWeight();
        //4、。。。等等其它类型同理

2、无返回值

@FunctionalInterface
public interface Consumer<T> {

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

范例:

        //Consumer无参数返回类型
        Consumer<Apple> appleConsumer = apple -> System.out.println(apple.getColor());
        Consumer<Apple> appleConsumer2 = apple -> System.out.println("hello");

3、返回Boolean类型

@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

范例:

        //Predicate返回Boolean类型(判断类型)
        Predicate<Apple> colorPredicate = apple -> apple.getColor().equals("red");
        Predicate<Apple> weightPredicate = apple -> apple.getWeight()==4;

4、获取对象

@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}get();
}
 

范例:

        //Supplier获取对象
        Supplier<Apple> appleSupplier = Apple::new;

根据上面3种接口,返回不同参数类型,在不同地方选择使用。

七、那些是FunctionInterface(函数式接口)

1、除了default、static的方法外,只有一个方法的接口,就是funcationInteface
    @FunctionalInterface
    interface Adder{
        int add(int a, int b);
    }
2、没有方法,但继承了有一个方法的接口是funcationInterface
    @FunctionalInterface
    interface Empty extends Adder{

    }

不是函数式接口的

1、继承后不止一个方法,因此不是funcationInterface
    interface SmartAdder extends Adder{
        int add(Long a, Long b);
    }
2、没有任何方法的接口,不是funcationInterface
    interface DoNothing{

    }
2

评论 (0)

取消