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) { ComparatorbyColor = new Comparator () { @Override public int compare(Apple o1, Apple o2) { return o1.getColor().compareTo(o2.getColor()); } }; //以前比较的写法 List list = Collections.emptyList(); list.sort(byColor); //Lambda表达式: 一个以上的参数,必须有括号 Comparator byColor2 = ((o1, o2) -> { return o1.getColor().compareTo(o2.getColor()); });
或
ComparatorbyColo3 = (o1, o2) -> o1.getColor().compareTo(o2.getColor());
} }
其他语法
Function : 给一个值,传出来另一个值
public interface Function{ /** * 将此函数应用于给定参数 * @param t * @return */ R apply(T t); }
Functionf = (a) -> a.getColor().equals("green"); Function flambda = s -> s.length();
示例:Function
public class lambdaExpression { private static String testFunction(Apple apple, Functionfun ){
//方法中只有一个参数 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
类中的方法 : R apply(T t, U u); // 根据输入的参数T和U , 得到输出参数 R
public class lambdaExpression { private static Apple testBiFunction(String c, double w, BiFunctionfun){ 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{ boolean test(T t); }
示例:
Predicatep = (Apple a) -> a.getColor().equals("green");
public class lambdaExpression {
private static Listfilter(List source, Predicate predicate ){
Listresult = new ArrayList<>();
for (Apple apple : source) {
if (predicate.test(apple)){
result.add(apple);
}
}
return result;
}
public static void main(String[] args) {
Listlist = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
//Predicate类中, 方法只有一个参数,下面的lambda表达式中 “()”可加可不加
ListappleList = filter(list, (apple) -> apple.getColor().equals("green"));
System.out.println(appleList);
}
}
BiPredicate: test方法有2个参数:
public class lambdaExpression { private static ListfilterByBiPredicate(List source, BiPredicate predicate ){ Listresult = 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 list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
//Predicate类中,方法有2个参数一定要用小括号包裹 ListappleList = filterByBiPredicate(list, (s, w) -> s.equals("green") && w > 100); System.out.println(appleList); } }
Supplier
Suppliersupplier = Apple::new;
示例:
public static void main(String[] args) {
//方法推导
Supplier 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(Listsource, Consumer consumer ){ Listresult = new ArrayList<>(); for (Apple apple : source) { consumer.accept(apple); } } public static void main(String[] args) { List 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, Listsource, BiConsumer consumer ){ Listresult = new ArrayList<>(); for (Apple apple : source) { consumer.accept(apple, c); } } public static void main(String[] args) { List 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{ /** * 将此函数应用于给定参数 * @param t * @return */ R apply(T t); }
Functionf = (a) -> a.getColor().equals("green"); Function flambda = s -> s.length();
示例:Function
public class lambdaExpression {
private static String testFunction(Apple apple, Function 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
类中的方法 : R apply(T t, U u); // 根据输入的参数T和U , 得到输出参数 R
public class lambdaExpression { private static Apple testBiFunction(String c, double w, BiFunctionfun){ 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{ boolean test(T t); }
示例:
Predicatep = (Apple a) -> a.getColor().equals("green");
public class lambdaExpression {
private static Listfilter(List source, Predicate predicate){
Listresult = new ArrayList<>();
for (Apple apple : source) {
if (predicate.test(apple)){
result.add(apple);
}
}
return result;
}
public static void main(String[] args) {
Listlist = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
//Predicate类中, 方法只有一个参数,下面的lambda表达式中 “()”可加可不加
ListappleList = filter(list, (apple) -> apple.getColor().equals("green"));
System.out.println(appleList);
}
}
BiPredicate: test方法有2个参数:
public class lambdaExpression { private static ListfilterByBiPredicate(List source, BiPredicate predicate){ List 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 list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
//Predicate类中,方法有2个参数一定要用小括号包裹 ListappleList = filterByBiPredicate(list, (s, w) -> s.equals("green") && w > 100); System.out.println(appleList); } }
Supplier
Suppliersupplier = Apple::new;
示例:
public static void main(String[] args) { //方法推导 Suppliers = 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(Listsource, Consumer consumer){ List result = new ArrayList<>(); for (Apple apple : source) { consumer.accept(apple); } } public static void main(String[] args) { List 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, Listsource, BiConsumer consumer){ List result = new ArrayList<>(); for (Apple apple : source) { consumer.accept(apple, c); } } public static void main(String[] args) { List 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
Functionfun = Integer::parseInt; Integer result = fun.apply("123"); System.out.println(result);
public class MethodReference { private staticvoid userConsumer(Consumer consumer, T t){ consumer.accept(t); consumer.accept(t); } public static void main(String[] args) { //以前lambda的方式 Consumer 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 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 ListfindApple(List apples, FilterApple filterApple){ List 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 findGreenApple(List apples){ List list = new ArrayList<>(); for (Apple apple : apples) { if ("green".equals(apple.getColor())){ list.add(apple); } } return list; } public static List findApple(List apples, String color){ List list = new ArrayList<>(); for (Apple apple : apples) { if (color.equals(apple.getColor())){ list.add(apple); } } return list; } public static void main(String[] args) { List list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 120), new Apple("green", 170)); // List appleList = findGreenApple(list); // assert appleList.size() == 2; // List greenApples = findApple(list, "green"); // System.out.println(greenApples); List apple = findApple(list, new GreenAnd150WeightFilter()); System.out.println(apple); List 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 ListfindApple(List apples, FilterApple filterApple){ List list = new ArrayList<>(); for (Apple apple : apples) { if (filterApple.filter(apple)){ list.add(apple); } } return list; } public static void main(String[] args) { List list = Arrays.asList(new Apple("green", 150), new Apple("yellow", 120), new Apple("green", 170)); //lambda表达式 List appleList = findApple(list, (Apple apple) -> { return apple.getColor().equals("green"); }); System.out.println(appleList); } }