138-139_容器_commons之函数式编程_Predicate_Transformer_Closure

这里写图片描述

Predicate

  • Test01_Predicate.java
package commons.collection;

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 
 * 3.判断唯一
 * UniquePredicate.uniquePredicate()
 * 4.自定义
 * new Predicate() + evaluate  
 * PredicateUtils.allPredicate(pre1,pre2...)  andPredicate anyPredicate
 * PredicatedXxx.predicatedXxx(容器,predicate)
 */

public class Test01_Predicate {
    public static void main(String[] args) {
        //equalPredicate(); 
        //notNullPredicate();
        //uniquePredicate();
        //defined();
    }
    /**
     * 1.比较相等判断-EqualPredicate
     */
    public static void equalPredicate(){
        System.out.println("======相等判断======");
        //Predicate<String> pre =new EqualPredicate<String>("bjsxt");
        Predicate<String> pre =EqualPredicate.equalPredicate("bjsxt");
        boolean flag =pre.evaluate("bj");
        System.out.println(flag);
    }
    /**
     * 2.判断非空-NotNullPredicate
     */
    public static void notNullPredicate(){
        System.out.println("====非空判断====");
        //Predicate notNull=NotNullPredicate.INSTANCE;
        Predicate<Object> notNull=NotNullPredicate.notNullPredicate();
        //String str ="bjs";
        String str =null;
        System.out.println(notNull.evaluate(str)); //如果非空为true ,否则为false

        //添加容器值的判断
        List<Long> list =PredicatedList.predicatedList(new ArrayList<Long>(), notNull);
        list.add(1000L);
        list.add(null); //验证失败,出现异常
    }
    /**
     * 3.判断唯一-UniquePredicate
     */
    public static void uniquePredicate(){
        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); //出现重复值,抛出异常
    }

    /**
     * 4.自定义判断-new Predicate() + evaluate 
     */
    public static void defined(){
        System.out.println("======自定义判断======");
        //自定义的判别式
        Predicate<String> selfPre =new Predicate<String>(){
            @Override
            public boolean evaluate(String object) {
                return object.length()>=5 && object.length()<=20;

            }};
        Predicate<String> notNull=NotNullPredicate.notNullPredicate();

        @SuppressWarnings("unchecked")
        Predicate<String> all =PredicateUtils.allPredicate(notNull,selfPre);

        List<String> list =PredicatedList.predicatedList(new ArrayList<String>(),all);
        list.add("bjsxt");
        list.add(null);
        list.add("bj"); 
    }
}

Transformer

  • Employee.java
package commons.collection;
/**
 * 员工类
 */

public 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 "(码农:"+this.name+",敲砖钱:"+this.salary+")";
    }
}
  • Level.java
package commons.collection;
/**
 * 等级类
 */
public 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 "(码农:"+this.name+",水平:"+this.level+")";
    }
}
  • Test02_Transformer.java
package commons.collection;

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(类型转化)
 *  Transformer<I, O> transformer=new Transformer<I, O>() {
        @Override
        public O transform(I input) {
            return null;
        }
    };
 * 1.内置类型的转换
 *   new Transformer() +transform
 *   CollectionUtils.collect(容器,转换器)
 * 2.自定义类型转换
 *   SwitchTransformer
 *   CollectionUtils.collect(容器,转换器)
 */

public class Test02_Transformer {
    public static void main(String[] args) {
        innerTransformer();//内置类型转换
        definedTransformer();//自定义类型转换
    }
    /**
     * 1.内置类型的转换-new Transformer() +transform
     */
    public static void innerTransformer(){
        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(999999999999L);
        list.add(300000000L);

        //工具类 程序猿出钱---开发商---农民工出力
        Collection<String>  result=CollectionUtils.collect(list, trans);
        //遍历查看结果
        for(String time:result){
            System.out.println(time);
        }
    }
    /**
     * 2.自定义类型转换-SwitchTransformer
     */
    public static void definedTransformer(){
        System.out.println("===自定义类型转换==");
        //判别式
        Predicate<Employee> isLow=new Predicate<Employee>(){
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary()<10000;
            }
        };
        Predicate<Employee> isHigh=new Predicate<Employee>(){
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary()>=10000;
            }
        };
        @SuppressWarnings("rawtypes")
        Predicate[] pres ={isLow,isHigh};

        //转换
        Transformer<Employee,Level> lowTrans =new Transformer<Employee,Level>(){
            @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(),"养身中");
            }};
        @SuppressWarnings("rawtypes")
        Transformer[] trans ={lowTrans,highTrans};  

        //二者进行了关联
        @SuppressWarnings("unchecked")
        Transformer<Employee, Level> switchTrans =new SwitchTransformer<Employee, Level>(pres, trans, null);

        //容器
        List<Employee> list =new ArrayList<Employee>();
        list.add(new Employee("老马",1000000));
        list.add(new Employee("老裴",999));

        Collection<Level> levelList = CollectionUtils.collect(list,switchTrans);
        //遍历容器
        Iterator<Level> levelIt =levelList.iterator();
        while(levelIt.hasNext()){
            System.out.println(levelIt.next());
        }
    }

}

Closure

  • Employee.java
package commons.collection;
/**
 * 员工类
 */

public 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 "(码农:"+this.name+",敲砖钱:"+this.salary+")";
    }
}
  • Goods.java
package commons.collection;

public class Goods {
    private String name;
    private double price;
    //折扣
    private boolean discount;
    public Goods() {
        // TODO Auto-generated constructor stub
    }
    public Goods(String name, double price, boolean discount) {
        super();
        this.name = name;
        this.price = price;
        this.discount = discount;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public boolean isDiscount() {
        return discount;
    }
    public void setDiscount(boolean discount) {
        this.discount = discount;
    }

    @Override
    public String toString() {
        return "(商品:"+this.name+",价格:"+this.price+",是否打折:"+(discount?"是":"否")+")";
    }
}
  • Test03_Closure.java
package commons.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.functors.ChainedClosure;
import org.apache.commons.collections4.functors.IfClosure;
import org.apache.commons.collections4.functors.WhileClosure;

/**
 * 函数式编程之Closure(闭包 封装特定的业务功能)
 * 1.基本操作
 *   Closure
 * 2.IfClosure  
 *   IfClosure.ifClosure(断言,功能1,功能2)
 * 3.WhileClosure 
 *   WhileClosure.whileClosure(断言,功能,标识) 
 * 4.ChainedClosure.chainedClosure(功能列表);
 *   CollectionUtils.forAllDo(容器,功能类对象);
 */

public class Test03_Closure {
    public static void main(String[] args) {
        //basic();      
        //ifClosure();
        //whileClosure();
        //chainClosure();
    }
    /**
     * 1.基本操作-Closure
     */
    @SuppressWarnings("deprecation")
    public static void basic(){
        //数据
        List<Employee> empList =new ArrayList<Employee>();
        empList.add(new Employee("bjsxt",20000));
        empList.add(new Employee("is",10000));
        empList.add(new Employee("good",5000));

        //业务功能
        Closure<Employee> closure=new Closure<Employee>(){
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary()*1.2);
            }};

        //工具类
        CollectionUtils.forAllDo(empList, closure)  ;
        //操作后的数据
        Iterator<Employee> empIt=empList.iterator();
        while(empIt.hasNext()){
            System.out.println(empIt.next());
        }
    }
    /**
     * 2.二选一  如果是打折商品,进行9折,否则满百减20
     *   IfClosure
     */
    @SuppressWarnings("deprecation")
    public static void ifClosure(){
        List<Goods> goodsList =new ArrayList<Goods>();
        goodsList.add(new Goods("javase视频",120,true));
        goodsList.add(new Goods("javaee视频",100,false));
        goodsList.add(new Goods("高新技术视频",80,false));

        //满百减20
        Closure<Goods> subtract=new Closure<Goods>(){
            public void execute(Goods goods) {
                if(goods.getPrice()>=100){
                    goods.setPrice(goods.getPrice()-20);
                }
            }};
        //打折
        Closure<Goods> discount=new Closure<Goods>(){
            public void execute(Goods goods) {
                if(goods.isDiscount()){
                    goods.setPrice(goods.getPrice()*0.9);
                }
            }}; 
        //判断
        Predicate<Goods> pre=new Predicate<Goods>(){
            public boolean evaluate(Goods goods) {
                return goods.isDiscount();
            }}; 

        //二选一
        Closure<Goods> ifClosure=IfClosure.ifClosure(pre, discount,subtract);

        //关联
        CollectionUtils.forAllDo(goodsList,ifClosure);

        //查看操作后的数据
        for(Goods temp:goodsList){
            System.out.println(temp);
        }
    }
    /**
     * 3.确保所有的员工工资都大于10000,如果已经超过的不再上涨
     *   WhileClosure
     */
    @SuppressWarnings("deprecation")
    public static void whileClosure(){
        //数据
        List<Employee> empList =new ArrayList<Employee>();
        empList.add(new Employee("bjsxt",20000));
        empList.add(new Employee("is",10000));
        empList.add(new Employee("good",5000));

        //业务功能 每次上涨0.2 
        Closure<Employee> closure=new Closure<Employee>(){
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary()*1.2);
            }};

        //判断
        Predicate<Employee> empPre=new Predicate<Employee>(){
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary()<10000;
            }           
        };  
        //false 表示 while结构 先判断后执行   true do..while 先执行后判断
        Closure<Employee> whileclosure =WhileClosure.whileClosure(empPre, closure, false);

        //工具类
        CollectionUtils.forAllDo(empList, whileclosure) ;

        //操作后的数据
        Iterator<Employee> empIt=empList.iterator();
        while(empIt.hasNext()){
            System.out.println(empIt.next());
        }
    }
    /**
     * 4.折上减   先打折商品,进行9折,满百再减20
     *   ChainedClosure
     */
    @SuppressWarnings({ "deprecation", "unchecked" })
    public static void chainClosure(){
        List<Goods> goodsList =new ArrayList<Goods>();
        goodsList.add(new Goods("javase视频",120,true));
        goodsList.add(new Goods("javaee视频",100,false));
        goodsList.add(new Goods("高新技术视频",80,false));

        //满百减20
        Closure<Goods> subtract=new Closure<Goods>(){
            public void execute(Goods goods) {
                if(goods.getPrice()>=100){
                    goods.setPrice(goods.getPrice()-20);
                }
            }};
        //打折
        Closure<Goods> discount=new Closure<Goods>(){
            public void execute(Goods goods) {
                if(goods.isDiscount()){
                    goods.setPrice(goods.getPrice()*0.9);
                }
            }}; 

        //链式操作
        Closure<Goods> chainclosure=ChainedClosure.chainedClosure(discount,subtract);

        //关联
        CollectionUtils.forAllDo(goodsList,chainclosure);

        //查看操作后的数据
        for(Goods temp:goodsList){
            System.out.println(temp);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值