例子是求一个班级中有几个学生大于20岁,共有四种方案。
(1)stutent类
package com.august.function;
/**
* Created by baimq on 2017/7/18.
*/
public class Student {
private String sex;
private int age;
private String name;
public Student(String name,String sex,int age){
this.name=name;
this.sex=sex;
this.age=age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(2)四种实现方案
package com.august.function;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by baimq on 2017/7/18.
*/
public class FunctionProgramming {
public static void main(String[] args) {
//求大于20岁的学生有几个人的四种写法
List<Student> studentList=new ArrayList<Student>();
Student student1=new Student("张三","男",23);
Student student2=new Student("李四","女",19);
Student student3=new Student("王五","男",21);
studentList.add(student1);
studentList.add(student2);
studentList.add(student3);
//1、for循环【java5以上均支持】【有状态记录,业务与逻辑耦合】
int olderThanTwenty=0;
for(Student student:studentList){
if(student.getAge()>20){
olderThanTwenty++;
}
}
System.out.println(olderThanTwenty);
//2、函数式思想编程【java5以上均支持】【无状态记录,业务与逻辑分离】
olderThanTwenty =CollectionUtils.countMatches(studentList, new Predicate() {
@Override
public boolean evaluate(Object o) {
Student student = (Student) o;
return student.getAge() > 20;
}
});
System.out.println(olderThanTwenty);
//3、函数式编程【java8以上均支持】
olderThanTwenty=CollectionUtils.countMatches(studentList, (arg0) -> ((Student) arg0).getAge()>20);
System.out.println(olderThanTwenty);
//4、函数式编程【java8以上均支持】
olderThanTwenty= (int) studentList.stream().filter(student -> student.getAge()>20).count();
System.out.println(olderThanTwenty);
}
}