java8四大基本函数式接口

  java8中提供了四个内置的函数式接口,通过直接使用这四个接口,或者使用它们的扩展接口,可以让我们很方便的使用lambda表达式。

1. Consumer<T> 消费型接口

@FunctionalInterface
public interface Consumer<T> {
 
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
}
  • 例子
import java.util.function.Consumer;

@Test
public consumerTest() {
	// 消费型接口  有参数,无返回值
    Consumer<String> consumer = t -> {
    	System.out.println(t);
    };
    consumer.accept("consumer");
}

输出:consumer

2. Supplier<T> 提供型接口

@FunctionalInterface
public interface Supplier<T> {

   /**
    * Gets a result.
    *
    * @return a result
    */
   T get();
}
  • 例子
import java.util.function.Supplier;

@Test
public supplierTest() {
	// 供给型接口  无参数,有返回值
    Supplier<String> supplier = () -> {
    	return  "supplier";
    };
    System.out.println(supplier.get());
}

输出:supplier

3. Function<T, R> 函数型接口

@FunctionalInterface
public interface Function<T, R> {
 
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
}
  • 例子
import java.util.function.Function;

@Test
public functionTest() {
	// 函数型接口 有参数,有返回值
	Function<Integer, Integer> function = s -> {
    	return s*2;
    };
    System.out.println(function.apply(1));
}

输出:2

4. Predicat<T> 断言型接口

@FunctionalInterface
public interface Predicate<T> {
 
    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
}
  • 例子
import java.util.function.Predicate;

@Test
public predicateTest() {
	//断定型接口 有参数,返回值为boolean
    Predicate<String> predicate = s ->{
    	if (s == "predicate") {
			return true;    	
    	}
    	return false;
    };
    System.out.println(predicate.test("predicate"));
}

输出:ture

参考文献

  • https://blog.csdn.net/weixin_41751625/article/details/105903106
  • https://www.jianshu.com/p/e55989015413
  • https://blog.csdn.net/qq_41835813/article/details/106359068
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值