常用函数式接口 lambda

这篇博客介绍了Java中的函数式接口,包括Supplier、Consumer、Predicate和Function接口。Supplier接口用于生产数据,Consumer接口用于消费数据,Predicate接口用于数据判断,Function接口用于数据转换。文章通过代码实例详细讲解了这些接口的使用,如lambda表达式的应用、接口的默认方法如andThen等,展示了如何在实际编程中灵活运用这些接口。
摘要由CSDN通过智能技术生成

概念

在Java中是指:有且仅有一个抽象方法的接口。

格式

修饰符 interface 接口名称 {
    public abstract 返回值类型 方法名称(可选参数信息);
    // 其他非抽象方法内容
}
public class Demo09FunctionalInterface {   
        // 使用自定义的函数式接口作为方法参数    
        private static void doSomething(MyFunctionalInterface inter) {    
            inter.myMethod(); // 调用自定义的函数式接口方法        
        }    
   
        public static void main(String[] args) {    
             // 调用使用函数式接口的方法        
            doSomething(()> System.out.println("Lambda执行啦!"));        
        }    
}

特性

​ 延迟执行

使用

  1. 先定义一个函数式接口A(只含有一个 抽象方法B
  2. 然后再定义一个方法C,参数含有接口A
  3. 方法C中调用接口A抽象方法B

测试:

调用方法C时,使用lamdba表达式实现 抽象方法B

代码:

//先定义一个函数式接口A(只含有一个 抽象方法B)
@FunctionalInterface
public static void InterfaceA(){
    void  methodB();
}
//然后再定义一个方法C,参数含有接口A
public static void showC(InterfaceA iA){
   iA.methodB();
}
//主函数调用
public static void main(String[] args){
    showC(()->{
        System.out.println("此处是methodB的方法体,通过lamdba方式表示")
    });
}

常用函数式接口

在java.util.function包中提供

supplier接口(生产型接口)

Supplier(T)

接口中含有 一个get方法 用来获取一个泛型参数指定类型的对象数据

作用
  • 通过方法调用产生一个数据(生产)
代码实例
private static String getString(Supplier<String> funciton){
        return funciton.get();
    }
    public static void main(String[] args){
        String s1 = "hello";
        String s2 = "world";

        //返回拼接字符
        String s3 = getString(()->{
            return s1+s2;
        });
        System.out.println(s3); //输出 helloworld
    }

//小案例:返回最大数值
private static int getMaxValue(Supplier<Integer> sup){
    return sup.get();
}

public static void main(String[] args){
   int[] arr = new int{1,2,33,55,222,100};
   int max = getMaxValue(()->{
        int t = arr[0];
       for(int i : arr){
           if(t<i){
               t = i;
           }
       }
       return t;
    });
    System.out.println("最大值"+max)}

Comsumer接口(消费型接口)

此接口则正好与Supplier接口相反,它不是生产一个数据,而是消费一个数据,其数据类型由泛型决定。

作用

通过 接口中内部方法 accept方法 消费指定类型的数据。

private static void comsumerString(Consumer<String> funciton){
   funciton.accept("hello world");
}
public static void main(String[] args){
    comsumerString((s)->{
        //消费方式 打印输出
        System.out.println(s);
    });
}
默认方法 andThen方法

andThen 的语义:“一步接一步”操作

一个方法的参数和返回值全都是 Consumer 类型,那么就可以实现效果:消费数据的时候,首先做一个操作,然后再做一个操作,实现组合。

private static void comsumerString(Comsunmer<String> one,Comsumer<String> two){
    one.andThen(two),accept("hello");
}
public static void main(String[] args){
    comsumerString(
        s-> System.out.println(s.toUpperCase());
        s->System.out.println(s.toLowerCase());
}

Predicate接口(判断型口)

抽象方法 Test(T t)

作用

需要对某种类型的数据进行判断,从而得到一个boolean值结果。

默认方法

有 and (并且) or(或者) negate(取非)

AND

如何使用 :< >.and < >.test( )

//传入参数
Predicate<String> one, Predicate<String> two 
one.and(two).test("Helloworld");
OR

如何使用 :< >.or< >.test( )

//传入参数
Predicate<String> one, Predicate<String> two 
one.or(two).test("Helloworld");
negate

如何使用

//传入参数
predicte cc
cc.negate() 
//调用方法
predicate.negate().test("HelloWorld");

小案例:

数组当中有多条“姓名+性别”的信息如下,请通过 Predicate 接口的拼装将符合要求的字符串筛选到集合
ArrayList 中,需要同时满足两个条件:

  1. 必须为女生;
  2. 姓名为4个字。

public class DemoPredicate {
    
    private static String method(String[] arr,Predicte<String> Pnv,Predicte<String> Str4){
        
       //添加进 集合中
        List<String> list = new ArratList<>;
        //遍历 传入的String类型的数组 
        for(String ss:array){
            //符合 2个判断接口条件的 添加进list中
            if(Pnv.and(Str4).test(ss)){
                list.add(ss);
            }
        }
        //返回list
       return list;
    }
    
    public static void main(String[] args) {
       String[] array = { "迪丽热巴,女", "古力娜扎,女", "马尔扎哈,男", "赵丽颖,女" };  
       List<String> list =method(array,
            //必须为女生;
            (String s)->{
                "女".equals(s.split(",")[1]);
            },
            (String s)->{
            //姓名为4个字
            s.split(",")[0].lenth()==4;
        });
        System.out.println(list);
    }
}


Function 接口

最主要的抽象方法为: R apply(T t)

作用

用一中类型的数据 来得到另外一种数据。将 R 类型的数据 转换为 T类型数据

默认方法:andThen 先做什么,再做什么

小案例

请使用 Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
String str = “赵丽颖,20”;

  1. 将字符串截取数字年龄部分,得到字符串;
  2. 将上一步的字符串转换成为int类型的数字;
  3. 将上一步的int数字累加100,得到结果int数字。
public class DemoFunction {
    public static void main(String[] args) {
        String str = "赵丽颖,20";
        filter(str.
              (s)->{s.sqlit(",")[1]},	  //将字符串截取数字年龄部分,得到字符串;
              (s)->{Integer.parseInt(s)}, //将上一步的字符串转换成为int类型的数字;
              (n)->{n +=100})			 //将上一步的int数字累加100,得到结果int数字。private static void filter(String str,Function<String Integer> one , Function<String Integer> two,Function<Integer Integer> three){
        one.andThen(two).andThen(three).apply(str);
    }
        
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值