来源:http://www.bjsxt.com/
1、S02E138_01commons之函数式编程1_Predicate_Transformer
Apache Commons Collections
——Commons-Collections:提供一个类包来扩展和增加标准的Java Collection框架,处理数据灵活
——下载地址:http://commons.apache.org/collections/
————MapIterator:很好用,以后不用map.keyset.iterator去处理map循环了
——HashedMap
————BidiMap:用于通过value查找key
——TreeBidiMap
————Bag:用于在集合中保存一个对象的多次拷贝
——HashBag
————Queue:用于处理FIFO等定义好移除顺序的集合类
————CollectionUtils:工具类
————Predicate:用来评估某个判别式或者条件,进行筛选,可以将其理解为对if条件的一种封装,该接口的唯一方法evaluate()返回true或false
————Transformer:用来将一个对象作为参数,返回一个经过转换处理后的新的对象
————Closure:闭包,封装功能,实现解耦
package com.test.commons;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.functors.EqualPredicate;
import org.apache.commons.collections4.functors.NotNullPredicate;
import org.apache.commons.collections4.functors.UniquePredicate;
import org.apache.commons.collections4.list.PredicatedList;
/**
* 函数式编程之Predicate 断言
* 理解为:封装条件或判别式 if...else...的替代
* 解耦:元素的判断与容器的操作分离
* 1.new EqualPredicate<类型>(值)
* EqualPredicate.equalPredicate(值)
*
* 2.NotNullPredicate.INSTANCE
* NotNullPredicate.notNullPredicate()
*
* 3.UniquePredicate.uniquePredicate()
*
* 4.自定义:new Predicate<类型>(){重写evaluate方法}
* PredicateUtils.allPredicate andPredicate anyPredicate
*
* 附带判断的容器:PredicatedXxx.predicatedXxx(容器,判断)
*/
public class TestPredicate {
public static void main(String[] args) {
testEqual();
testNotNull();
testUnique();
testSelf();
}
/**
* 相等判断
*/
public static void testEqual(){
System.out.println("============相等判断=============");
Predicate<String> pre1 = new EqualPredicate<String>("abcd");
System.out.println(pre1.evaluate("ab"));//返回false
//pre1 或者 pre2
Predicate<String> pre2 = EqualPredicate.equalPredicate("abcd");
System.out.println(pre2.evaluate("ab"));//返回false
}
/**
* 非空判断
*/
public static void testNotNull(){
System.out.println("================非空判断=================");
Predicate notNull1 = NotNullPredicate.INSTANCE;
String str1 = "abc";
System.out.println(notNull1.evaluate(str1));//返回true/如果非空为true,否则为false
//notNull1 或者 notNull2
Predicate notNull2 = NotNullPredicate.notNullPredicate();
String str2 = null;
System.out.println(notNull2.evaluate(str2));//返回false
//添加容器值的判断
List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(), notNull1);
list.add(1000L);
//list.add(null);//验证失败,出现异常
}
/**
* 唯一性判断
*/
public static void testUnique(){
System.out.println("================唯一性判断=================");
Predicate<Long> uniquePre = UniquePredicate.uniquePredicate();
List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(), uniquePre);
list.add(100L);
list.add(200L);
//list.add(100L);//出现重复值,抛出异常
}
/**
* 自定义判断
*/
public static void testSelf(){
System.out.println("============自定义判断============");
Predicate<String> selfPre = new Predicate<String>() {
@Override
public boolean evaluate(String object) {
return object.length() >=5 && object.length() <=20;
}
};
Predicate notNull = NotNullPredicate.notNullPredicate();
Predicate all = PredicateUtils.allPredicate(selfPre,notNull);
List<String> list = PredicatedList.predicatedList(new ArrayList<String>(), all);
list.add("abcde");
//list.add(null);//java.lang.NullPointerException
//list.add("abc");//java.lang.IllegalArgumentException
}
}
package com.test.commons;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.Transformer;
import org.apache.commons.collections4.functors.SwitchTransformer;
/**
* 解耦:业务处理与判断进行分离
* 函数式编程之Transformer 类型转换
* 1.内置类型转换:new Transformer(){重写transform}
* CollectionUtils.collect(容器, 转换器)
*
* 2.自定义类型转换
* new Predicate<类型>(){重写evaluate}
* new Transformer<被转换类型, 转换类型>(){重写transformer}
* new SwitchTransformer(Predicate, Transformer, null)//Predicate跟Transformer关联
* CollectionUtils.collect(容器, 转换器)
*/
public class TestTransformer {
public static void main(String[] args) {
testInnerTransformer();
testDefTransformer();
}
/**
* 内置类型转换:new Transformer(){重写transform}
*/
public static void testInnerTransformer(){
System.out.println("内置类型转换 长整型时间日期,转成指定格式的字符串");
//类型转换器
Transformer<Long, String> trans = new Transformer<Long, String>() {
@Override
public String transform(Long input) {
return new SimpleDateFormat("yyyy年MM月dd日").format(input);
}
};
List<Long> list = new ArrayList<Long>();
list.add(999999999999999L);
list.add(30000000000L);
System.out.println(list);//[999999999999999, 30000000000]
//类似:程序猿出钱---开发商(中介)---农民工出力 借助工具类
Collection<String> result = CollectionUtils.collect(list, trans);
System.out.println(result);//[33658年09月27日, 1970年12月14日]
}
/**
* 自定义类型转换
*/
public static void testDefTransformer(){
System.out.println("==============自定义类型转换===============");
//判别式
Predicate<Employee> isLow = new Predicate<Employee>() {
@Override
public boolean evaluate(Employee emp) {
return emp.getSalary() < 1000;
}
};
Predicate<Employee> isHigh = new Predicate<Employee>() {
@Override
public boolean evaluate(Employee emp) {
return emp.getSalary() >= 1000;
}
};
Predicate[] pres = {isLow,isHigh};
//转换
Transformer<Employee, Level> lowTrans = new Transformer<Employee, Level>() {
//Add unimplemented methods的快捷键:ctrl+1
@Override
public Level transform(Employee input) {
return new Level(input.getName(), "卖身中");
}
};
Transformer<Employee, Level> highTrans = new Transformer<Employee, Level>() {
@Override
public Level transform(Employee input) {
return new Level(input.getName(), "养身中");
}
};
Transformer[] trans = {lowTrans,highTrans};
//Predicate数组跟Transformer,二者进行关联
Transformer<Employee, Level> switchTrans = new SwitchTransformer<Employee, Level>(pres, trans, null);
//容器
List<Employee> list = new ArrayList<Employee>();
list.add(new Employee("张三", 10000000000000L));
list.add(new Employee("李四", 999));
Collection<Level> levelList = CollectionUtils.collect(list, switchTrans);
//遍历容器
Iterator<Level> levelIterator = levelList.iterator();
while (levelIterator.hasNext()) {
System.out.println(levelIterator.next());
}
/*
返回:
(码农:张三,水平:养身中)
(码农:李四,水平:卖身中)
*/
}
}
///
/**
* 员工类
*/
class Employee{
private String name;
private double salary;
//alt +/
public Employee() {
}
//alt+shift+s o
public Employee(String name, double salary) {
super();
this.name = name;
this.salary = salary;
}
//alt+shift+s +r tab 回车 shift+tab 回车
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "(码农:" + name + ",工资:" + salary +")";
}
}
/**
* 等级类
*/
class Level{
private String name;
private String level;
public Level() {
}
public Level(String name, String level) {
super();
this.name = name;
this.level = level;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
@Override
public String toString() {
return "(码农:" + name + ",水平:" + level +")";
}
}