首页 > 代码库 > 函数式编程的一些魅力
函数式编程的一些魅力
例子是求一个班级中有几个学生大于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);
}
}
函数式编程的一些魅力
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。