码迷,mamicode.com
首页 > 其他好文 > 详细

函数式编程的一些魅力

时间:2017-07-19 00:21:47      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:object   collect   main   状态   comm   static   org   commons   []   

例子是求一个班级中有几个学生大于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);

}
}

函数式编程的一些魅力

标签:object   collect   main   状态   comm   static   org   commons   []   

原文地址:http://www.cnblogs.com/baimingqian/p/7203433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!