Java四大内置核心函数式接口
快速滑到底部大约1.5秒,认真看完大约6分钟
使用Lambda表达式需要用到函数式接口,我们可以根据自己的需求来定义想要的函数式接口,下面定义一个简单的操作字符串的函数式接口,并使用它,看看效果
//1.自己定义函数式接口public interface MyFunction {String getValue(String s);}// 2.用于处理字符串的方法public String strHandler(String str,MyFunction mf){return mf.getValue(str);}// 3.测试结果public void test5(){String trim = strHandler("A Thousand Years",(s) -> s.toLowerCase());System.out.println(trim);//输出:a thousand years}
其实大部分的函数式接口Java已经帮我们定义好了,我们直接拿来用就可以,其中最常用的是如下四种类型的接口,接下来看看接口的定义和使用:
1.Consumer<T> 消费型接口
// 1.接口的定义public interface Consumer<T> {void accept(T t);}// 2.定义一个方法,主要关注参数Consumer<Double> consumer:public void happy(double money, Consumer<Double> consumer){consumer.accept(money);}// 3.测试一下public void test(){happy(1000D,m-> System.out.println("去召唤师峡谷消费:" + m + "元"));}//输出:去召唤师峡谷消费:1000.0元
2.Supplier<T>: 供给型接口
// 1.接口定义public interface Supplier<T> {T get();}// 2.定义一个方法public List<Integer> getNumList(int num, Supplier<Integer> sup){List<Integer> list = new ArrayList<>();for(int i = 0;i < num;i++){list.add(sup.get());//sup.get()}return list;}// 产生一些整数,并放入集合中,接口实现:() -> (int) (Math.random() * 10)public void sup(){List<Integer> numList = getNumList(5, () -> (int) (Math.random() * 10));for(Integer num : numList){System.out.print(num + " ");//打印结果:7 4 0 0 1}}
3.Function<T,R>: 函数型接口
// 1. 接口定义public interface Function<T, R> {R apply(T t);}// 2public String strHandler(String str, Function<String,String> function){return function.apply(str);}// 3public void func(){String aaaaa = strHandler("aaaaa", (x) -> x.toUpperCase());System.out.println(aaaaa);// 输出:AAAAAString aa = strHandler("abcdefg", (x) -> x.substring(2,5));System.out.println(aa);// 输出:cde}
4.Predicate<T>: 断言型接口
// 1public interface Predicate<T> {boolean test(T t);}// 2public List<String> filterStr(List<String> list, Predicate<String> predicate){List<String> stringList = new ArrayList<>();for(String str : list){if(predicate.test(str)){ // predicate.test(str)stringList.add(str);}}return stringList;}// 3public void pre(){List<String> list = Arrays.asList("damon","AI","lambda","James","allen","Kobe");// 过滤掉长度小于等于4的字符串List<String> list1 = filterStr(list, (s) -> s.length() > 4);list1.stream().forEach(e-> System.out.print(e + " "));// 输出:damon lambda James allen}
四种内置核心函数接口就介绍到这,希望对你有帮助。
你在看吗 祝你今天愉快!
