函数式接口习题

基础题

练习一:函数式接口

  1. 定义一个函数式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(),使用注解@FunctionalInterface
  2. 在测试类中定义static void showLongTime(CurrentTimePrinter timePrinter),该方法的预期行为是使用timePrinter打印系统当前毫秒值
  3. 测试showLongTime(),通过lambda表达式完成需求

 

答案

TimePrinter接口:

@FunctionalInterface
public interface CurrentTimePrinter

{
    void printCurrenTime();
}

测试类:

public class Test01 {
    public static void main(String[] args) {
        showLongTime(()->System.out.println(System.currentTimeMillis()));
    }

    public static void showLongTime(CurrentTimePrinter timePrinter){
        timePrinter.printCurrentTime();
    }
}

 

练习二:函数式接口

  1. 定义一个函数式接口IntCalc,其中抽象方法int calc(int a , int b),使用注解@FunctionalInterface
  2. 在测试类中定义static void getProduct(int a , int b ,IntCalc calc), 该方法的预期行为是使用calc得到a和b的乘积并打印结果
  3. 测试getProduct(),通过lambda表达式完成需求

 

答案

IntCalc接口:

@FunctionalInterface
public interface IntCalc {
    int calc(int a, int b);
}

测试类:

public class Test02 {
    public static void main(String[] args) {
        getProduct(2,3,(a,b)->a*b);
    }
    public static void getProduct(int a, int b, IntCalc intCalc){
        int product = intCalc.calc(a,b);
        System.out.println(product);

    }
}

练习三:静态方法引用

  1. 定义一个函数式接口NumberToString,其中抽象方法String convert(int num),使用注解@FunctionalInterface
  2. 在测试类中定义static void decToHex(int num ,NumberToString nts), 该方法的预期行为是使用nts将一个十进制整数转换成十六进制表示的字符串,tips:已知该行为与Integer类中的toHexString方法一致
  3. 测试decToHex (),使用方法引用完成需求

 

答案

NumberToString接口:

@FunctionalInterface
public interface NumberToString {
    String convert(int num);
}

测试类:

public class Test03 {
    public static void main(String[] args) {
        decToHex(999, Integer::toHexString);
    }
    public static void decToHex(int num ,NumberToString nts){
        String convert = nts.convert(num);
        System.out.println(convert);
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值