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"; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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()); } } |
其他语法
1 | Function : 给一个值,传出来另一个值 |
1 2 3 4 5 6 7 8 | public interface Function<T, R>{ /** * 将此函数应用于给定参数 * @param t * @return */ R apply(T t); } |
1 2 | Function<Apple, Boolean> f = (a) -> a.getColor().equals( "green" ); Function<String, Integer> flambda = s -> s.length(); |
示例:Function
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | 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 :
1 2 3 | public interface Predicate<T>{ boolean test(T t); } |
1 | <strong>示例:</strong> |
1 | 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个参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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();
1 | Supplier<Apple> supplier = Apple:: new ; |
示例:
1 2 3 4 5 | public static void main(String[] args) { //方法推导 Supplier<String> s = String:: new ; System.out.println(s.get().getClass()); } |
Consumer :
1 | /**<br> * Performs this operation on the given argument.<br> * params : t -- the input argument<br> */ <br> void accept(T t); |
示例:Consumer中有一个参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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中是两个参数的情况:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 : 给一个值,传出来另一个值
1 2 3 4 5 6 7 8 | public interface Function<T, R>{ /** * 将此函数应用于给定参数 * @param t * @return */ R apply(T t); } |
1 2 | Function<Apple, Boolean> f = (a) -> a.getColor().equals( "green" ); Function<String, Integer> flambda = s -> s.length(); |
示例:Function
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | 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 :
1 2 3 | public interface Predicate<T>{ boolean test(T t); } |
1 | <strong>示例:</strong> |
1 | Predicate<Apple> p = (Apple a) -> a.getColor().equals( "green" );<br><br> public class lambdaExpression {<br><br> private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate){<br> List<Apple> result = new ArrayList<>();<br> for (Apple apple : source) {<br> if (predicate.test(apple)){<br> result.add(apple);<br> }<br> }<br> return result;<br> }<br><br> public static void main(String[] args) {<br> List<Apple> list = Arrays.asList( new Apple( "green" , 120 ), new Apple( "red" , 150 ));<br> //Predicate类中, 方法只有一个参数,下面的lambda表达式中 “()”可加可不加<br> List<Apple> appleList = filter(list, (apple) -> apple.getColor().equals("green"));<br> System.out.println(appleList);<br> }<br>} |
BiPredicate<T, U>: test方法有2个参数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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();
1 | Supplier<Apple> supplier = Apple:: new ; |
示例:
1 2 3 4 5 | public static void main(String[] args) { //方法推导 Supplier<String> s = String:: new ; System.out.println(s.get().getClass()); } |
Consumer :
1 | /**<br> * Performs this operation on the given argument.<br> * params : t -- the input argument<br> */ <br> void accept(T t); |
示例:Consumer中有一个参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 ));<br> //Consumner中的accept方法有一个参数 simpleTestConsumer(list, a -> System.out.println(a)); } } |
示例: Consumer中是两个参数的情况:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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);
1 2 3 | Function<String, Integer> fun = Integer::parseInt; Integer result = fun.apply( "123" ); System.out.println(result); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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)
实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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 + '}' ; } } |
利用接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix