Lambda(二)lambda表達式使用 Lambda 表達式組成: Lambda表達式需要有與之相匹配的預定義函數式介面: 簡單使用案例,source code 如下 假如,現在要對Apple的list進行排序(常規vsLambda): 自定義使用,source code如下 ...
Lambda(二)lambda表達式使用
Lambda 表達式組成:
/* param list arrow lambda body (o1,o2) -> o1.getColor().CompareTo(o2.getColor()); */
Lambda表達式需要有與之相匹配的預定義函數式介面:
/* FunctionalInterface介面:Predicate<T> 方法:Boolean test(T t); FunctionalInterface介面:Consume<T> 方法:void accept(T t); FunctionalInterface介面:Function<T,R> 方法:R apply(T t); FunctionalInterface介面:Suppiler<T> 方法:T get(); */
簡單使用案例,source code 如下
Consumer<String> c = s -> System.out.println(s); Function<String,Integer> lambda = s->s.length(); Predicate<Apple> predicate = a->a.getColor().equals("green"); Function<Apple,Boolean> function = a->a.getColor().equals("red"); Supplier<Apple> instance = Apple::new;
假如,現在要對Apple的list進行排序(常規vsLambda):
//implement item1 list.sort(new Comparator<Apple>() { @Override public int compare(Apple o1, Apple o2) { return o1.getColor().compareTo(o2.getColor()); } }); //implement item2 list.sort((o1, o2) -> o1.getColor().compareTo(o2.getColor())); //implement item2 list.sort(comparing(Apple::getColor));
自定義使用,source code如下
public static List<Apple> filter(List<Apple> apples, Predicate<Apple> predicate){ List<Apple> result = new ArrayList<>(); for(Apple a:apples){ if(predicate.test(a)){ result.add(a); } } return result; } public static void main(String[] args) { List<Apple> apples = Arrays.asList(new Apple("green", 120), new Apple("red", 150)); List<Apple> green = filter(apples, a -> a.getColor().equals("green")); System.out.println(green); }
java 8 API中最多只有兩個入參,假如有多個參數,可以自己定義,source code如下
//自定義FunctionalInterface介面 @FunctionalInterface public interface ThreeFunction<T,U,K,R> { R apply(T t,U u,K k); } //具體使用 ThreeFunction<String,Long,String,ComplexApple> tf = ComplexApple::new; ComplexApple cp = tf.apply("yellow", 111L, "fushi"); System.out.println(cp);
方法推導(MethodReference):
/** * 使用方法推導的條件: * 1、類的實例方法 * 2、對象的實例方法 * 3、構造函數 */ public static <T> void useConsume(Consumer<T> consumer,T t){ consumer.accept(t); } useConsume(System.out::println,"chuangg"); List<Apple> apples = Arrays.asList(new Apple("red", 100), new Apple("green", 150), new Apple("abc", 110)); apples.stream().forEach(System.out::println); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> int i = Integer.parseInt("123"); Function<String,Integer> f = Integer::parseInt; Integer apply = f.apply("123"); System.out.println(apply); BiFunction<String, Integer, Character> f1 = String::charAt; Character r1 = f1.apply("hello", 2); System.out.println(r1); String s = new String("hello"); Function<Integer, Character> f2 = s::charAt; Character r2 = f2.apply(1); System.out.println(r2); Supplier<Apple> appleSupplier = Apple::new; Apple apple = appleSupplier.get(); BiFunction<String,Long,Apple> appleBiFunction = Apple::new; Apple blue = appleBiFunction.apply("blue", 123L); System.out.println(blue);