1. 程式人生 > >138-139_容器_commons之函數語言程式設計_Predicate_Transformer_Closure

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);
        }
    }
}