函数式接口

概述

  • 函数式接口:接口中只有一个抽象方法的接口
  • 可以使用注解@FunctionalInterface修饰,可以检查是否是函数式接口
1 @FunctionalInterface
2 public interface Runnable {
3     public abstract void run();
4 }

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

  • Consumer<T>:消费型接口  void accept(T t)

1     public static void main(String[] args) {
2         happy(1000, (m) -> System.out.println("昨天花费了" + m + "元。"));
3     }
4 
5     public static void happy(double money, Consumer<Double> consumer) {
6         consumer.accept(money);
7     }
  • Supplier<T>:供给型接口  T get()

 1     public static void main(String[] args) {
 2         List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
 3         for (Integer num : numList) {
 4             System.out.println(num);
 5         }
 6     }
 7     public static List<Integer> getNumList(int num, Supplier<Integer> supplier) {
 8         List<Integer> list = new ArrayList<>();
 9 
10         for (int i = 0; i < num; i++) {
11             Integer value = supplier.get();
12             list.add(value);
13         }
14 
15         return list;
16     }
  • Function<T, R>:函数型接口  R apply()

1     public static void main(String[] args) {
2         String newStr = strHandler("\t\t\t  hmz        ", (str) -> str.trim());
3         System.out.println(newStr);
4     }
5     public static String strHandler(String str, Function<String, String> function) {
6         return function.apply(str);
7     }
  • Predicate<T>:断言型接口  boolean test(T t)

 1     public static void main(String[] args) {
 2         List<String> list = Arrays.asList("hello", "world", "Lambda", "hmz", "ok");
 3         List<String> filterList = filterStr(list, (s) -> s.length() > 3);
 4         System.out.println(filterList);
 5     }
 6 
 7     public static List<String> filterStr(List<String> list, Predicate<String> predicate) {
 8         List<String> stringList = new ArrayList<>();
 9 
10         for (String str : list) {
11             if (predicate.test(str)) {
12                 stringList.add(str);
13             }
14         }
15 
16         return stringList;
17     }

转载于:https://www.cnblogs.com/HNewa/p/Java_Functional_Interface.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值