Java8 - 内置四大核心函数式接口

Java8提供的四大核心函数接口如下

接口 方法 描述
Comsumer<T> void accept (T t) 消费型接口
Supplier<T> T get() 供给型接口
Function<T, R> R apply (T t) 函数型接口
Predicate<T> Boolean test (T t) 断言型接口

  1. Consumer消费者函数式接口
    用于消费一些服务,实例如下
/**
 * Comsumer Interface
 */
@Test
public void consumer() {
    consumerApply(1024D, x -> System.out.println("consume success - ") + x);
}
    
public void consumerApply(Double quantity, Consumer<Double> consumer) {
    consumer.accept(quantity);
}

输出:consume success - 1024.0


  1. 供给型函数式接口
    用于提供服务,实例如下
/**
 * Supplier Interface
 */
@Test
public void supplier() {
    Double randomNum = getRandomDouble(() -> Math.random());
    System.out.println(randomNum);
}
    
public Double getRandomDouble(Supplier<Double> supplier) {
    return supplier.get();
}

输出:0.8422320267963174


  1. 函数型接口
    用于处理数据,返回一些相同或不同的数据类型,实例如下
/**
* Function Interface
*/
@Test
public void function() {
    Boolean result = backValue(2, x -> {
        if (x == 1) 
            return true;
        else 
            return false;
    });
        
        System.out.println(result);
    }
    
public Boolean backValue(Integer flag, Function<Integer, Boolean> function) {
    return function.apply(flag);
}

输出:false


  1. Predicate断言式接口
    用于处理满足条件的数据,如筛选大于3的元素置于一个新数组中,实例如下:
/**
 * Predicate Interface
 */
@Test
public void predicate() {
    List<Integer> numericeSet = new ArrayList<>();
    numericeSet.add(1);
    numericeSet.add(2);
    numericeSet.add(3);
    numericeSet.add(4);
    numericeSet.add(5);
        
    List<Integer> result = filteNumeric(numericeSet, x -> x > 3);
        
    System.out.println(Arrays.toString(result.toArray()));
}

public List<Integer> filteNumeric(List<Integer> numericeSet, Predicate<Integer> predicate) {
        
    List<Integer> collection = new ArrayList<>();
        
    if (numericeSet.size() > 0) {
            
        for (Integer tmp : numericeSet) {
            if (predicate.test(tmp)) {
                collection.add(tmp);
            }
        }
    }
        
    return collection;
}

输出:[4, 5]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容