欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java8新特性之函数式接口

程序员文章站 2022-05-22 19:22:12
...

Java8内置函数式接口

Consumer< T > :消费者接口

@Test
public void test01(){
    //Consumer
    Consumer<Integer> consumer = (x) -> System.out.println("消费" + x);
    //test
    consumer.accept(1000);
}

Supplier< T > : 供给型接口

  @Test
    public void test04 () {
        List list = getNum (10, () -> (int) (Math.random () * 100));
        list.forEach (System.out :: println);
    }

	//返回num个随机数
    public List<Integer> getNum (int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<> ();
        for (int i = 0; i < num; i++) {
            list.add (supplier.get ());
        }
        return list;
    }

Function< T, R > : 函数型接口

@Test
    public void test05 () {
        String s = strHandler (" 156 1CNDJINCD bjc AGVCHSDBCK  ", String :: toLowerCase);
        System.out.println (s);
    }

    public String strHandler (String str, Function<String, String> function) {
        return function.apply (str);
    }

Predicate< T > : 断言型接口

@Test
public void test04(){
    Integer age = 70;
    Predicate<Integer> predicate = (i) -> i >= 35;
    if (predicate.test(age)){
        System.out.println("你该退休了");
    } else {
        System.out.println("hhh");
    }
}

其他接口

Java8新特性之函数式接口

自定义函数式接口

@FunctionalInterface
public interface MyFunction {
    Integer count(Integer a, Integer b);
}

@Test
public void test05(){
    Integer result = operation(3, 5, (x, y) -> x + y);
    System.out.println(result);
}

public Integer operation(Integer a, Integer b, MyFunction myFun){
    return myFun.count(a, b);
}
相关标签: Java8新特性