java8部分理解

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package org.sang.plugins.test;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.function.*;

@Slf4j
public class Temp {
/**
*
*
* Function<T, R>:接受一个参数输入,输入类型为 T,输出类型为 R。 抽象方法为R apply(T)。
* BiFunction<T, U, R>:接受两个参数输入, T 和 U 分别是两个参数的类型,R 是输出类型。抽象方法为R apply(T, U)。
* Consumer:接受一个输入,没有输出。抽象方法为 void accept(T t)。
* Predicate:接受一个输入,输出为 boolean 类型。抽象方法为 boolean test(T t)。
* Supplier:没有输入,一个输出。抽象方法为 T get()。
* BinaryOperator:接受两个类型相同的输入,输出的类型与输入相同,相当于 BiFunction<T,T,T>。
* UnaryOperator:接受一个输入,输出的类型与输入相同,相当于 Function<T, T>。
* BiPredicate<T, U>:接受两个输入,输出为 boolean 类型。抽象方法为 boolean test(T t, U u)。
*
*/
Function<Integer,Integer> A= i->i+1;
BiFunction<Integer,Integer,Integer> B =(a,b)->a+b+1;
Consumer c = (i)-> System.out.println(i);
Predicate d = (b)->false;
Supplier e = ()->"gg";
BinaryOperator<Integer> cal = (a, b) -> a + b;
static Supplier<Integer> multiply0_a = ()->2;

static UnaryOperator<Integer> multiply1_a = (x)->x*2;
static Function<Integer,Integer> multiply1_b = (x)->x*2;

static BinaryOperator<Integer> multiply2_a = (a, b)->a*b;
static BiFunction<Integer,Integer,Integer> multiply2_b = (a, b)->a*b;

static TriOperator<Integer> multiply3_a = (a, b,c)->a*b*c;
static TriFunction<Integer,Integer,Integer,Integer> multiply3_b = (a, b, c)->a*b*c;

@FunctionalInterface
public interface TriFunction<A,B,C,R>{
R apply(A t,B u,C v);
}
@FunctionalInterface
public interface TriOperator<T> extends TriFunction<T,T,T,T>{
// static <T> TriOperator<T> minBy() {
// return (a,b,c) -> comparator.compare(a, b) <= 0 ? a : b;
// }
}


static <A,B,C> Function<A,C> compose(Function<B,C> g, Function<A,B> f){
return x-> g.apply( f.apply(x));
}
static <A> Function<A,A> repeat(int n,Function<A,A> f){
return n==0? x->x :compose(f,repeat(n-1,f));
}
static Function<Integer,Integer> multiply(Integer a){
return x->x*a;
}
/**
* 理解级联 lambda 表达式
*/
private void testLambda(){
List<Integer> numbers = Arrays.asList(2, 5, 8, 15, 12, 19, 50, 23);
Function<Integer, Predicate<Integer>> isGreaterThan = pivot -> candidate -> candidate > pivot;
numbers.stream().filter(isGreaterThan.apply(12)).forEach(System.out::println);
}

/**
* - Optional.of(T t) : 创建一个 Optional 实例
* - Optional.empty() : 创建一个空的 Optional 实例
* - Optional.ofNullable(T t):若 t 不为 null,创建 Optional 实例,否则创建空实例
* - isPresent() : 判断是否包含值
* - orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
* - orElseGet(Supplier s) :如果调用对象包含值,返回该值,否则返回 s 获取的值
* - map(Function f): 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
* - flatMap(Function mapper):与 map 类似,要求返回值必须是Optional
*
*/


}