函数式编程

1. lambda表达式

2. 函数式接口

2.1 Consumer 函数型接口

点击查看代码
public class demo1 {
    public static void main(String[] args) {
     /*   Consumer<Double> consumer = new Consumer<Double>() {
            @Override
            public void accept(Double money) {
                System.out.println("消费 = " + money);
            }
        };
        happy(consumer,100);*/
        happy(money-> System.out.println("消费 = " + money),100);
    }

    public static void happy(Consumer<Double> consumer,double money) {
        consumer.accept(money);
    }
}

2.3 Function 函数型接口

通过传递不同的 Function 实例,你可以让 handlerString 方法执行多种操作,而不需要修改 handlerString 的实现。例如,你可以很容易地改变行为来将字符串转换为大小写、反转字符串等,只需传入不同的 Function 实现即可。

点击查看代码
//Function 函数型接口
public class Demo3 {
    public static void main(String[] args) {
     /*   Function<String, String> function = new Function<String, String>() {
            @Override
            public String apply(String s) {
                return s.toLowerCase();
            }
        };*/
        // 转换为小写
        Function<String, String> function = (String s) -> s.toLowerCase();
        String result1 = handlerString(function, "ABC");
        // 转换为大写
        String result2 = handlerString(s -> s.toUpperCase(),"abc");
        System.out.println(result1);
        System.out.println(result2);
    }
    public static String handlerString(Function<String, String> function, String str) {
        return function.apply(str);
    }
}

2.4 Predict断言型接口

点击查看代码
//Function 断言型接口
public class Demo4 {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("zhangsan", "lisi", "wangwu");
   /*     Predicate<String> predict = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.startsWith("zh");
            }
        };
        List<String> result = filterNames(predict, list);*/
        List<String> result =filterNames(s -> s.startsWith("zh"),list);
        System.out.println(result);

    }


    public static List<String> filterNames(Predicate<String> predicate, List<String> names) {
        List<String> result = new ArrayList<>();
        for (String name : names) {
            if (predicate.test(name)) {
                result.add(name);
            }
        }
        return result;
    }
}

3. 方法引用

posted @ 2024-10-13 16:33  piqigoo  阅读(4)  评论(0编辑  收藏  举报