java8新特性之函数式接口
四大核心函数式接口
函数式接口 | 参数类型 | 返回类型 | 使用场景 |
---|---|---|---|
Consumer消费型接口 | T | void | 对类型为T的对象应用操作,接口定义的方法:voidaccept(T t) |
Supplier供给型接口 | 无 | T | 返回类型为T的对象,接口定义的方法:T get() |
Function<T,R>函数式接口 | T | R | 对类型为T的对象应用操作,并R类型的返回结果。接口定义的方法:R apply(T t) |
Predicate断言型接口 | T | boolean | 确定类型为T的对象是否满足约束条件,并返回boolean类型的数据。接口定义的方法:boolean test(T t) |
四大核心函数式接口解析及简要代码
注:以四大核心函数式为例。之后以此类推掌握其他函数式接口使用
Consumer接口
Consumer接口是消费性接口,无返回值
public void consumer(String str, Consumer<String> con){
con.accept(str);
}
@Test
public void test3(){
consumer("sdaas",s -> {
String s1 = s.toUpperCase();
System.out.println(s1);
});
}
suppiler接口
Supplier接口是供给型接口,有返回值
public List<Integer> supplier(Integer qew, Supplier<Integer> supplier){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < qew; i++) {
list.add(supplier.get());
}
return list;
}
@Test
public void test3(){
List<Integer> numberList = supplier(10, () -> new
Random().nextInt(100));
numberList.stream().forEach(System.out::println);
}
Function接口
Function接口是函数型接口,有返回值
public String handlerString(String str, Function<String, String> func){
return func.apply(str);
}
@Test
public void test3(){
String wewewr = handlerString("wewewr", s -> s.toUpperCase());
System.out.println(wewewr);
}
Predicate接口
Predicate接口是断言型接口,返回值类型为boolean
public List<String> filterString(List<String> list, Predicate<String> predicate){
List<String> strList = new ArrayList<>();
for(String str : list){
if(predicate.test(str)){
strList.add(str);
}
}
return strList;
}
@Test
public void test4(){
List<String> list = Arrays.asList("Hello", "Lambda", "binghe", "lyz",
"World");
List<String> strList = this.filterString(list, (s) -> s.length() >= 5);
strList.stream().forEach(System.out::println);
}
其他函数式接口
函数式接口 | 参数类型 | 返回类型 | 使用场景 |
---|---|---|---|
BiFunction(T, U, R) | T,U | R | 对类型为T,U的参数应用操作,返回R类型的结果。接口定义的方法:R apply(T t, Uu) |
UnaryOperator(Function子接口) | T | T | 对类型为T的对象进行一 元运算, 并返回T类型的 结果。 包含方法为 T apply(T t) |
BinaryOperator(BiFunction 子接口) | T,T | T | 对类型为T的对象进行二 元运算, 并返回T类型的 结果。 包含方法为 T apply(T t1,T t2) |
BiConsumer<T, U> | T,U | void | 对类型为T, U 参数应用 操作。 包含方法为 void accept(T t, U u) |
ToIntFunction | T | int | 计算int值的函数 |
ToLongFunction | T | long | 计算long值的函数 |
ToDoubleFunction | T | duble | 计算double值的函数 |
IntFunction | int | R | 参数为int 类型的函数 |
LongFunction | long | R | 参数为log 类型的函数 |
DoubleFunction | duble | R | 参数为duble 类型的函数 |