java8 lambda表达式的基本语法

java8 lambda表达式: 可以很清晰的定义或展示一个匿名的函数

一、lambda的语法

  parameter list 部分             lambd body部分

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

lambda语法:
  • (parameters) -> expression
  • (parameters) -> { statments; }
例子:
  () -> {};
  () -> { return "Hello"; }
  () -> { return "Hello World"; }
  (Integer i) -> return "Alex" + i invalid;
  (String s) -> { return "Hello Alex"; }

public class lambdaExpression {
    public static void main(String[] args) {
        Comparator<Apple> byColor = new Comparator<Apple>() {
            @Override
            public int compare(Apple o1, Apple o2) {
                return o1.getColor().compareTo(o2.getColor());
            }
        };
        //以前比较的写法
        List<Apple> list = Collections.emptyList();
        list.sort(byColor);

        //Lambda表达式: 一个以上的参数,必须有括号
        Comparator<Apple> byColor2 = ((o1, o2) -> {
            return o1.getColor().compareTo(o2.getColor());
        });

     或
    Comparator<Apple> byColo3 = (o1, o2) -> o1.getColor().compareTo(o2.getColor());
    }
}

  其他语法

Function 给一个值,传出来另一个值
public interface Function<T, R>{
     /**
      * 将此函数应用于给定参数
      * @param t
      * @return
      */
    R apply(T t);
}

 

Function<Apple, Boolean> f = (a) -> a.getColor().equals("green");
Function<String, Integer> flambda = s -> s.length();

  示例:Function

public class lambdaExpression {

    private static String testFunction(Apple apple, Function<Apple, String> fun){
//方法中只有一个参数 return fun.apply(apple); } public static void main(String[] args) { Apple apple = new Apple("green", 120);
// Function类中,apply方法只有一个参数,括号可加可不加 String s = testFunction(apple, a -> a.toString()); System.out.println(s); } }

  示例: BiFunction<T, U, R>  

   类中的方法 :  R apply(T t, U u);  // 根据输入的参数T和U , 得到输出参数 R
public class lambdaExpression {

    private static Apple testBiFunction(String c, double w, BiFunction<String, Double, Apple> fun){
       return fun.apply(c, w);
    }

    public static void main(String[] args) {
     //BiFunction类中, apply方法有两个参数,lambda表达式之针对这些特定的函数
        Apple apple = testBiFunction("yellow", 123, (c, w) -> new Apple(c, w));
        System.out.println(apple);
    }
}

 

 

Predicate :

public interface Predicate<T>{
   boolean test(T t);
}
示例:
Predicate<Apple> p = (Apple a) -> a.getColor().equals("green");

public class lambdaExpression {

private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate){
List<Apple> result = new ArrayList<>();
for (Apple apple : source) {
if (predicate.test(apple)){
result.add(apple);
}
}
return result;
}

public static void main(String[] args) {
List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //Predicate类中, 方法只有一个参数,下面的lambda表达式中 “()”可加可不加
List<Apple> appleList = filter(list, (apple) -> apple.getColor().equals("green"));
System.out.println(appleList);
}
}

  

BiPredicate<T, U>: test方法有2个参数:
public class lambdaExpression {

    private static List<Apple> filterByBiPredicate(List<Apple> source, BiPredicate<String, Double> predicate){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            if (predicate.test(apple.getColor(), apple.getWeight())){
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //Predicate类中,方法有2个参数一定要用小括号包裹 List<Apple> appleList = filterByBiPredicate(list, (s, w) -> s.equals("green") && w > 100); System.out.println(appleList); } }

Supplier<T>: 方法: T get(); 

Supplier<Apple> supplier = Apple::new;

  示例: 

public static void main(String[] args) {
    //方法推导
    Supplier<String> s = String::new;
    System.out.println(s.get().getClass());
}

 

Consumer : 

/**
* Performs this operation on the given argument.
* params : t -- the input argument
*/
void accept(T t);

   示例:Consumer中有一个参数

public class lambdaExpression {
   //Consumer类中,方法是一个参数的情况
    private static void simpleTestConsumer(List<Apple> source, Consumer<Apple> consumer){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            consumer.accept(apple);
        }
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //Consumner中的accept方法有一个参数 simpleTestConsumer(list, a -> System.out.println(a)); } }

  示例: Consumer中是两个参数的情况:

public class lambdaExpression {
  //BiConsumer类中, 方法有两个参数的情况
    private static void simpleTestBiConsumer(String c, List<Apple> source, BiConsumer<Apple, String> consumer){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            consumer.accept(apple, c);
        }
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //lambda表达式,根据方法中的参数个数来 simpleTestBiConsumer("XXX-", list, (a, s) -> System.out.println(s+ "color:" + a.getColor()+", weight:"+a.getWeight())); } }

  

二、如何使用lambda

public class lambdaExpression {
    public static void main(String[] args) {
        Runnable r1 = () -> System.out.println("Hello");

        Runnable r2 = new Runnable() {
            @Override
            public void run() {
                System.out.println("HEllo");
            }
        };

     //这三种调用情况是一样的 process(r1); process(r2); process(() -> System.out.println("Hello")); } private static void process(Runnable r){ r.run(); }
}

  

三、execute around pattern

 

四、函数式接口(Functional interfaces)

 函数式接口:接口上面都有一个注解@FunctionalInterface

Function : 给一个值,传出来另一个值

public interface Function<T, R>{
     /**
      * 将此函数应用于给定参数
      * @param t
      * @return
      */
    R apply(T t);
}

 

Function<Apple, Boolean> f = (a) -> a.getColor().equals("green");
Function<String, Integer> flambda = s -> s.length();

  示例:Function

public class lambdaExpression {

    private static String testFunction(Apple apple, Function<Apple, String> fun){
//方法中只有一个参数 return fun.apply(apple); } public static void main(String[] args) { Apple apple = new Apple("green", 120);
// Function类中,apply方法只有一个参数,括号可加可不加 String s = testFunction(apple, a -> a.toString()); System.out.println(s); } }

  示例: BiFunction<T, U, R>  

   类中的方法 :  R apply(T t, U u);  // 根据输入的参数T和U , 得到输出参数 R
public class lambdaExpression {

    private static Apple testBiFunction(String c, double w, BiFunction<String, Double, Apple> fun){
       return fun.apply(c, w);
    }

    public static void main(String[] args) {
     //BiFunction类中, apply方法有两个参数,lambda表达式之针对这些特定的函数
        Apple apple = testBiFunction("yellow", 123, (c, w) -> new Apple(c, w));
        System.out.println(apple);
    }
}

 

Predicate :

public interface Predicate<T>{
   boolean test(T t);
}
示例:
Predicate<Apple> p = (Apple a) -> a.getColor().equals("green");

public class lambdaExpression {

private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate){
List<Apple> result = new ArrayList<>();
for (Apple apple : source) {
if (predicate.test(apple)){
result.add(apple);
}
}
return result;
}

public static void main(String[] args) {
List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //Predicate类中, 方法只有一个参数,下面的lambda表达式中 “()”可加可不加
List<Apple> appleList = filter(list, (apple) -> apple.getColor().equals("green"));
System.out.println(appleList);
}
}

  

BiPredicate<T, U>: test方法有2个参数:
public class lambdaExpression {

    private static List<Apple> filterByBiPredicate(List<Apple> source, BiPredicate<String, Double> predicate){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            if (predicate.test(apple.getColor(), apple.getWeight())){
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //Predicate类中,方法有2个参数一定要用小括号包裹 List<Apple> appleList = filterByBiPredicate(list, (s, w) -> s.equals("green") && w > 100); System.out.println(appleList); } }

Supplier<T>: 方法: T get(); 

Supplier<Apple> supplier = Apple::new;

  示例: 

public static void main(String[] args) {
    //方法推导
    Supplier<String> s = String::new;
    System.out.println(s.get().getClass());
}

 

Consumer : 

/**
* Performs this operation on the given argument.
* params : t -- the input argument
*/
void accept(T t);

   示例:Consumer中有一个参数

public class lambdaExpression {
   //Consumer类中,方法是一个参数的情况
    private static void simpleTestConsumer(List<Apple> source, Consumer<Apple> consumer){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            consumer.accept(apple);
        }
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //Consumner中的accept方法有一个参数 simpleTestConsumer(list, a -> System.out.println(a)); } }

  示例: Consumer中是两个参数的情况:

public class lambdaExpression {
  //BiConsumer类中, 方法有两个参数的情况
    private static void simpleTestBiConsumer(String c, List<Apple> source, BiConsumer<Apple, String> consumer){
        List<Apple> result = new ArrayList<>();
        for (Apple apple : source) {
            consumer.accept(apple, c);
        }
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
     //lambda表达式,根据方法中的参数个数来 simpleTestBiConsumer("XXX-", list, (a, s) -> System.out.println(s+ "color:" + a.getColor()+", weight:"+a.getWeight())); } }

  

五、方法推导(Method references)

 方法推导的适用条件:

类的静态方法:

Function<T, R>  --->  R apply(T t);

Function<String, Integer> fun = Integer::parseInt;
Integer result = fun.apply("123");
System.out.println(result);

  

public class MethodReference {


    private static <T> void userConsumer(Consumer<T> consumer, T t){
        consumer.accept(t);
        consumer.accept(t);
    }

    public static void main(String[] args) {
        //以前lambda的方式
        Consumer<String> consumer = (s) -> System.out.println(s);
        userConsumer(consumer, "Hello Alex");

        userConsumer(s -> System.out.println(s), "Hello1234");
        //方法推导
        userConsumer(System.out::println, "Hello wangwu099");
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
        //
        List<Apple> list = Arrays.asList(new Apple("green", 110), new Apple("abc", 150), new Apple("red", 170));
        System.out.println(list);

        list.sort((a1, a2) ->{ return a1.getColor().compareTo(a2.getColor()); });
        System.out.println(list);

     //方法推导
     list.stream().foreach(System.out::println);
} }

  

六、类型推导(Type inference)

 

七、组合(Composing lambdas)

 

实体类

public class Apple {

    private String color;
    private double weight;

    public Apple(String color, double weight) {
        this.color = color;
        this.weight = weight;
    }

    public double getWeight() {
        return weight;
    }

    public void setHeigh(double weight) {
        this.weight = weight;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "color='" + color + '\'' +
                ", weight=" + weight +
                '}';
    }
}

  利用接口

public class AppleFilter {

    public interface FilterApple{
        boolean filter(Apple apple);
    }

    public static List<Apple> findApple(List<Apple> apples, FilterApple filterApple){
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if (filterApple.filter(apple)){
                list.add(apple);
            }
        }
        return list;
    }

    public static class GreenAnd150WeightFilter implements FilterApple{
        @Override
        public boolean filter(Apple apple) {
            return (apple.getColor().equals("green")) && (apple.getWeight() >= 160);
        }
    }

    public static List<Apple> findGreenApple(List<Apple> apples){
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if ("green".equals(apple.getColor())){
                list.add(apple);
            }
        }
        return list;
    }

    public static List<Apple> findApple(List<Apple> apples, String color){
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if (color.equals(apple.getColor())){
                list.add(apple);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 120), new Apple("green", 170));
//        List<Apple> appleList = findGreenApple(list);
//        assert appleList.size() == 2;

//        List<Apple> greenApples = findApple(list, "green");
//        System.out.println(greenApples);

        List<Apple> apple = findApple(list, new GreenAnd150WeightFilter());
        System.out.println(apple);

        List<Apple> yellowApples = findApple(list, new FilterApple() {
            @Override
            public boolean filter(Apple apple) {
                return "yellow".equals(apple.getColor());
            }
        });
        System.out.println(yellowApples);

    }
}

  匿名内部类; 结果为: 5

public class MeaningOfThis {

    public final int value = 4;

    public void doIt() {
        int value = 6;
        Runnable r = new Runnable() {

            public final int value = 5;

            @Override
            public void run() {
                int value = 10;
                System.out.println(this.value);
            }
        };
        r.run();
    }

    public static void main(String[] args) {
        MeaningOfThis m = new MeaningOfThis();
        m.doIt();
    }
}

  lamda表达式

public class AppleFilter {

    public interface FilterApple{
        boolean filter(Apple apple);
    }

    public static List<Apple> findApple(List<Apple> apples, FilterApple filterApple){
        List<Apple> list = new ArrayList<>();
        for (Apple apple : apples) {
            if (filterApple.filter(apple)){
                list.add(apple);
            }
        }
        return list;
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 120), new Apple("green", 170));

        //lambda表达式
        List<Apple> appleList = findApple(list, (Apple apple) -> {
            return apple.getColor().equals("green");
        });

        System.out.println(appleList);

    }

}

  

 

posted @ 2022-04-13 12:01  IT6889  阅读(59)  评论(0编辑  收藏  举报