java8新特性之函数式接口

java8新特性之函数式接口

四大核心函数式接口

函数式接口参数类型返回类型使用场景
Consumer消费型接口Tvoid对类型为T的对象应用操作,接口定义的方法:voidaccept(T t)
Supplier供给型接口T返回类型为T的对象,接口定义的方法:T get()
Function<T,R>函数式接口TR对类型为T的对象应用操作,并R类型的返回结果。接口定义的方法:R apply(T t)
Predicate断言型接口Tboolean确定类型为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,UR对类型为T,U的参数应用操作,返回R类型的结果。接口定义的方法:R apply(T t, Uu)
UnaryOperator(Function子接口)TT对类型为T的对象进行一 元运算, 并返回T类型的 结果。 包含方法为 T apply(T t)
BinaryOperator(BiFunction 子接口)T,TT对类型为T的对象进行二 元运算, 并返回T类型的 结果。 包含方法为 T apply(T t1,T t2)
BiConsumer<T, U>T,Uvoid对类型为T, U 参数应用 操作。 包含方法为 void accept(T t, U u)
ToIntFunctionTint计算int值的函数
ToLongFunctionTlong计算long值的函数
ToDoubleFunctionTduble计算double值的函数
IntFunctionintR参数为int 类型的函数
LongFunctionlongR参数为log 类型的函数
DoubleFunctiondubleR参数为duble 类型的函数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值