什么是函数式编程
函数式编程并不是Java新提出的概念,其与指令编程相比,强调函数的计算比指令的计算更重要;与过程化编程相比,其中函数的计算可以随时调用。
当然,大家应该都知道面向对象的特性(抽象、封装、继承、多态)。其实在Java8出现之前,我们关注的往往是某一类对象应该具有什么样的属性,当然这也是面向对象的核心--对数据进行抽象。但是java8出现以后,这一点开始出现变化,似乎在某种场景下,更加关注某一类共有的行为(这似乎与之前的接口有些类似),这也就是java8提出函数式编程的目的。
列:
public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); studentList.add(new Student("sam", 12)); studentList.add(new Student("ali", 14)); studentList.add(new Student("summer", 50)); studentList.add(new Student("lucy", 18)); studentList.add(new Student("alie", 32)); studentList.add(new Student("kill", 22)); //函数式筛选年龄大于等于18岁的学生toList List<Student> listMap = studentList.stream().filter(student -> student.getAge() >= 18).collect(Collectors.toList()); //函数式调用大于18岁的学生toMap Map<Integer, List<Student>> map = studentList.stream().filter(student -> student.getAge() > 18).collect(Collectors.groupingBy(Student::getAge)); //函数式调用方法 studentList.sort(CouponServiceImpl::getCompart); //对列表进行排序 studentList.sort((s1, s2) -> { return s2.getAge().compareTo(s1.getAge()); }); //老式方法对列表进行排序 studentList.sort(new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { if (o1.getAge() > o2.getAge()) { return -1; } return 1; } }); //打印出学生年龄 studentList.forEach(student -> System.out.println(student.getAge())); } private static int getCompart(Student student1, Student student2) { return student2.getAge().compareTo(student1.getAge()); }
自定义函数式接口支持Lambda表达式
看下如下代码,最终输出应该是两行"Hello World!"
public class Main {
public static void main(String[] args) {
Action action = System.out :: println;
action.execute("Hello World!");
test(System.out :: println, "Hello World!");
}
static void test(Action action, String str) {
action.execute(str);
}
}
@FunctionalInterface
interface Action<T> {
public void execute(T t);
}