函数式接口

2020-07-18  本文已影响0人  hehehehe
约束:接口中只有一个抽象方法

(1)、只包含一个抽象方法的接口,称为函数式接口。
(2)、你可以通过Lambda表达式来创建该接口的对象。(若Lambda表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
(3)、我们可以在任意函数式接口上使用@FunctionalInterface注解,这样做可以检查它是否是一个函数式接口,同时javadoc也会包含一条声明,说明这个接口是一个函数式接口。

@FunctionInterface

函数接口可以被lambada表达式接收
匿名类也可以被lambada接收

Runnable 就是个函数接口,因此线程可以

 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}
public Thread(Runnable target) {
    init(null, target, "Thread-" + nextThreadNum(), 0);
}
new Thread(()-> System.out.println(123)).start();

自定义函数式接口

@FunctionalInterface
public interface TestFunction<T> {
    boolean test(T t);
}

static void sout(List<Integer>list, TestFunction testFunction){
   for (Integer integer : list) {
     System.out.println(testFunction.test(integer));
     }
 }

public static void main(String[] args) throws IOException {
    List<Integer> integers = Arrays.asList(1, 2, 3,4);
    sout(integers,(val)->{
         if ((Integer)val>3){
              return true;
         }else if ((Integer)val>1){
            return false;
         }
          else {
             return false;
         }
     });
        TestFunction<Integer> test =  (val)-> {
            if (val > 3) {
                return true;
            } else if (val > 1) {
                return false;
            } else {
                return false;
            }
        };
     new Thread(()-> System.out.println(123)).start();
  }
Java内置四大核心函数式接口
image.png
1、 Consumer<T> : 消费型接口,void accept(T t);
@Test
    public void test() {
        happy(10000,(m) -> System.out.println("花了:"+m));
    }
    public void happy(double  money,Consumer<Double> con) {
        con.accept(money);
    }
2、 Supplier<T> : 供给型接口,T get();
@Test
    public void test1() {
        List<Integer> numList = getNumList(10, ()->(int)(Math.random()*100 ));
        for (Integer integer : numList) {
            System.out.println(integer);
        }
    }
    //需求:产生指定个数的整数,并放入集合中
    public List<Integer> getNumList(int num,Supplier<Integer> sup){
            List<Integer> list = new ArrayList<>();
            for(int i=0;i<num;i++) {
                
                Integer n = sup.get();
                list.add(n);
                
            }
            return list;
    }
3、Function<T, R> : 函数型接口,R apply(T t);
@Test
    public void  test2() {
        String trimStr=strHandler("\t\t  你好,world!   ",(str) -> str.trim());
        System.out.println(trimStr);
        
        
        String sumString=strHandler("Helloworld!",(str)->str.substring(2, 4));
        System.out.println(sumString);
    }
    //需求:用于处理字符串
    public  String strHandler(String str,Function<String,String> fun) {
        return fun.apply(str);
    }
    
4、 Predicate<T> : 断言型接口,boolean test(T t);
    @Test
    public void test3() {
        List<String> list=Arrays.asList("Hello","world","hi","o","123");
        List<String> filterStr = filterStr(list, (str)->str.length()>1);
        for (String string : filterStr) {
            System.out.println(string);
        }
    }
    
    //需求:将满足条件的字符串,放入集合中
        public List<String> filterStr(List<String> list, Predicate<String> pre){
            List<String> list2=new ArrayList<>();

            for (String str : list) {
                if(pre.test(str)){
                    list2.add(str);
                }
            }
            
            return list2;
        }
上一篇 下一篇

猜你喜欢

热点阅读