Java函数式编程之Consumer

描述:Consumer< T>接口接受一个T类型参数,没有返回值。

源码如下:

@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
    
    ...
    
}

测试

定义一个Student类

public class Student {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }
    
    // getter setter
}

修改姓名和分数

Student student = new Student("Anson", 100);

Consumer<Student> consumer = new Consumer<Student>() {
    @Override
    public void accept(Student student) {
        student.setName("X-rapido");
        student.setScore(200);
    }
};

consumer.accept(student);

System.out.println("姓名:" + student.getName() + " ,分数:" + student.getScore());

// 运行结果
姓名:X-rapido ,分数:200

以上代码使用lambda简写如下

Consumer<Student> consumer = stu -> {
    stu.setName("X-rapido");
    stu.setScore(200);
};

java8以前的实现如下:

public void test(){
    Student student = new Student("Anson", 100);
    change(student);

    System.out.println("姓名:" + student.getName() + " ,分数:" + student.getScore());
}

private void change(Student stu){
    stu.setName("X-rapido");
    stu.setScore(200);
}

两相对比,使用函数式确实是要优雅一点。


赞(52) 打赏
未经允许不得转载:优客志 » JAVA开发
分享到:

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏