java 8功能性接口(Functional)

来源:互联网 发布:天下游是什么软件 编辑:程序博客网 时间:2024/05/21 13:55

Ø  JDK1.8包括了许多功能性接口。它们中的一些是老版本中被熟知的接口,例如Comparator和Runnable。这些已存在的接口已经通过@FunctionalInterface注解扩展为支持Lambda表达式。

 

Ø  在 Java 中,Marker(标记)类型的接口是一种没有方法或属性声明的接口,简单地说,marker 接口是空接口。相似地,函数式接口是只包含一个抽象方法声明的接口

 

Ø  每个 Lambda 表达式都能隐式地赋值给函数式接口,当不指明函数式接口时,编译器会自动解释这种转化

 

Ø  函数式接口例子:

Consumer<Integer>  c = (int x) -> { System.out.println(x) };
 
BiConsumer<Integer, String> b = (Integer x, String y) -> System.out.println(x + " : " + y);
 
Predicate<String> p = (String s) -> { s == null };

 

 

l  相关接口:

1.        断言接口(Predicates) 是只拥有一个参数的Boolean型功能的接口。这个接口拥有多个默认方法用于构成predicates复杂的逻辑术语

Predicate<String> predicate = (s) -> s.length() > 0;  
    predicate.test("foo");              // true  
    predicate.negate().test("foo");     // false  
 
    Predicate<Boolean> nonNull = Objects::nonNull;  
    Predicate<Boolean> isNull = Objects::isNull;  
 
    Predicate<String> isEmpty = String::isEmpty;  
    Predicate<String> isNotEmpty = isEmpty.negate();  

 

2.        功能接口(Functions)Functions接受一个参数并产生一个结果,默认方法能够用于将多个函数链接在一起。

Function<String, Integer> toInteger = Integer::valueOf;  
Function<String, Integer> backToString = toInteger.addThen(String::valueOf);

backToString.apply(“5120”);

3.        供应接口(Supplier) 对于给定的泛型类型产生一个实例。不同于Functions,Suppliers不需要任何参数。

    Supplier<Person> personSupplier = Person::new;  
    personSupplier.get();   // new Person 

 

 

4.        消费接口(Consumers)代表在只有一个输入参数时操作被如何执行

Consumer<Person> greeter = (p) -> System.out.println("Hello, " + p.firstName);  
    greeter.accept(new Person("Luke", "Skywalker"));  

5.        比较接口(Comparators)

 
   Comparator<Person> comparator= 
(p1, p2) -> p1.firstName.compareTo(p2.firstName);  
 
    Person p1 = new Person("John", "Doe");  
    Person p2 = new Person("Alice", "Wonderland");  
 
    comparator.compare(p1, p2);             // > 0  
   comparator.reversed().compare(p1, p2);  // < 0  

6.选项接口(Optionals)一种特殊的工具用来解决NullPointerException

    Optional<String> optional = Optional.of("bam");  
     optional.isPresent();           // true  
     optional.get();                 // "bam"  
     optional.orElse("fallback");    // "bam"  

optional.ifPresent((s)->System.out.println(s.charAt(0)));// "b"

自定义Functional接口

package com.ven.java8.functional.Interface;/** * 函数接口 * @author xiaowen0623 * */@FunctionalInterfacepublic interface ConvertFunctional<F,T> {    /**     * 转换方法     * @param f     * @return     */T convert(F f);}
测试:

package com.ven.java8.functional.Interface.test;import com.ven.java8.functional.Interface.ConvertFunctional;/** * 测试 * @author xiaowen * */public class TestFunctional {public static void main(String[] args) {ConvertFunctional<String,Integer> convert = (from) -> Integer.valueOf(from); Integer result = convert.convert("123");System.err.println(result);}}



0 0
原创粉丝点击