java8之Lambda表达式 2:内建函数式接口

从jdk1.8开始为了方便用户开发专门提供了一个新的包:java.util.function,在这个包里面针对于用户有可能做的函数式接口做了一个公共定义。在java.util.function包中最为核心的有四个接口:

  • 功能型接口:Function
  • 消费型接口:Consumer
  • 供给型接口:Supplier
  • 断言形接口:Predicate

1. 功能型接口

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);//接收数据而后返回处理结果
}

范例:实现功能型接口的使用
本次引用Integer类的parseInt()方法,这个方法要求接收String型数据,而后返回int型数据。

public class TestDemo {
    public static void main(String[] args) {
        Function<String,Integer> fn=Integer::parseInt;
        int num=fn.apply("100");
        System.out.println(num*2);
    }
}

也就是说这种既能输入数据,又能返回结果的方法,都可以用Function接口定义。

2. 消费型接口:Consumer

首先来观察Consumer接口的定义:

@FunctionalInterface
public interface Consumer<T>{
    public void accept(T t);//只接收数据,并没有返回值
}

范例:使用消费型接口,引用System.out.println()方法

public class TestDemo {
    public static void main(String[] args) {
        Consumer<String> con =System.out :: println;
        con.accept("Hello Lambda");
    }
}

3. 供给型:Supplier

接口定义:

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

本接口的方法没有参数,但是可以返回数据。
范例:设置供给型方法引用,System.currentTimeMillis

public class TestDemo {
    public static void main(String[] args) {
        Supplier<Long> sup=System::currentTimeMillis;
        System.out.println(sup.get());
    }
}

4. 断言型接口 :Predicate

首先观察接口定义:

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

范例:引用String类中的matches方法

public class TestDemo {
    public static void main(String[] args) {
        String str="100";
        Predicate<String> pre=str::matches;
        System.out.println(pre.test("\\d+"));
    }
}

以上四个是核心接口,其他接口与其都相似。以BiFunction为例,此接口定义如下:

@FunctionalInterface
public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}

虽然与Function接口不同,但是这里面可以设置两个参数。
范例:利用BiFunction接口引用String类的replaceAll()方法

public class TestDemo {
    public static void main(String[] args) {
        String str="hello";
        BiFunction<String,String,String> bf =str::replaceAll;
        System.out.println(bf.apply("l", "-"));//输出he--o
    }
}

之所以提供函数式的接口,那么他也会在系统类库里面大量出现。
在Collection接口里面新定义了一个forEach()方法,default void forEach(Consumer

public class TestDemo {
    public static void main(String[] args) {
        List<String> pro=new ArrayList<String>();
        pro.add("java");
        pro.add("android");
        pro.add("ios");
        pro.add("python");
        pro.add("node.js");
        pro.add("html");
        pro.forEach((s)->System.out.println(s));
        pro.forEach(s->System.out.println(s));//如果只有一个参数,直接编写也可以,不用写()
    }
}

由于内建的函数式接口提供,所以让开发标准进行了同意,日后用户不再需要自己开发函数式接口,直接使用java.util.function包中的接口即可。

你可能感兴趣的:(java,lambda)