java-函数式接口练习

函数式接口练习

目录

       这是我从网上看到的题目,自己看题目,自己写代码,只注重了功能,但是没有主动效率之类的。这次的三个题目比较简单,主要是函数式接口很抽象,如果代码短一些还好,如果长的,简直就是天书啊,根本跟平时人类的思考方式一点都不一样。

题目1

  1. 第一题

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

    代码如下:

@FunctionalInterface
public interface CurrentTimePrinter {
    void printCurrentTime();
}
public class Test01 {

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

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

题目2

  1. 第二题

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

    代码如下:

@FunctionalInterface
public interface IntCalc {
    int calc(int a,int b);
}
public class Demo2 {
    public static void getProduct(int a,int b,IntCalc calc){
            int result = calc.calc(a,b);
        System.out.println(result);
    }

    public static void main(String[] args) {
        getProduct(1,5,(a,b)-> {return a*b;});
    }
}

题目3

  1. 第三题

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

    代码如下:

@FunctionalInterface
public interface NumberToString {
    String convert(int num);
}
public class Demo3 {
    public static void decToHex(int num,NumberToString nts){
        String s = nts.convert(num);
        System.out.println(s);
    }
    public static void main(String[] args) {
        decToHex(11,num -> { return Integer.toHexString(num);});
        decToHex(12,Integer::toHexString);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值