1. 程式人生 > >Appache的commons之函數語言程式設計(一)

Appache的commons之函數語言程式設計(一)

 注意  : 我使用jar包是commons-collections4-4.1.jar appache下的 各位不要導錯

Predicate簡單的使用

package com.hp.common;

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;
import org.apache.commons.collections4.map.PredicatedMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 函數語言程式設計 -->Predicate
 */
public class Demo01 {
    public static void main(String[] args) {
        System.out.println("######相等判斷");
        boolean equalsePredicate = equalePredicate();
        System.out.println(equalsePredicate);
        System.out.println("####為空判斷");
        boolean str = notNull(null);
        System.out.println(str);
        System.out.println("####對集合進行的操作  判斷集合是否為空");
        predicateList();

        System.out.println("####判斷map是否為空");
        predicateMap();


        System.out.println("######唯一性判斷");
        unionPredicate();

        System.out.println("#####z自定義驗證");
        customPridicate();
    }


    /**
     * 比較相等的判斷 相等返回true  不等返回false
     *
     * @return
     */
    public static boolean equalePredicate() {
        //相當於if  else 的替代
        //第一種需要 new EqualPredicate<String>("hello")
        // Predicate<String> hello = new EqualPredicate<String>("hello");
        //第二種 不需要new 物件 裡面有封裝好的方法
        Predicate<String> hello = EqualPredicate.equalPredicate("hello");
        //判斷是否相等
        return hello.evaluate("hello");
    }

    /**
     * 對單個字元  進行判斷是否為空  如果不為空返回true 為空返回false
     *
     * @param str
     * @return
     */
    public static boolean notNull(String str) {
        Predicate predicate = NotNullPredicate.INSTANCE;
        return predicate.evaluate(str);
    }


    /**
     * 對list集合進行非空判斷
     */
    public static void predicateList() {
        Predicate<Object> predicate = NotNullPredicate.notNullPredicate();
        List<Long> predicatedList = PredicatedList.predicatedList(new ArrayList<>(), predicate);
        predicatedList.add(123L);
        //java.lang.IllegalArgumentException:  如果為空就會報錯
        //predicatedList.add(null);
        System.out.println(predicatedList.size());
    }


    /**
     *
     */
    public static void predicateMap() {
        Predicate<String> key = NotNullPredicate.notNullPredicate();
        Predicate<Integer> values = NotNullPredicate.notNullPredicate();
        Map<String, Integer> map = PredicatedMap.predicatedMap(new HashMap<String, Integer>(), key, values);
        map.put("123", 1);
        map.put("123", 32);
        //如果key 為空
        // map.put(null,1);   Cannot add key - Predicate rejected it錯誤
        //如果val 為空
        //map.put("1232",null);  Cannot add value - Predicate rejected it
        //如果key 和 val 都為空  -->說明先判斷key 是否為空  如果key為空  則val不再進行判斷
        //map.put(null, null);   Cannot add key - Predicate rejected it

        //迴圈map
        map.keySet().stream().forEach(e -> System.out.println("key  -->" + e + "   val-->" + map.get(e)));
    }

    /**
     * 唯一性判斷
     */
    public static void unionPredicate() {
        Predicate<String> predicate = UniquePredicate.uniquePredicate();
        List<String> list = PredicatedList.predicatedList(new ArrayList<>(), predicate);
        list.add("zs");
        // list.add("zs");   丟擲異常  Cannot add Object 'zs' - Predicate  不能重複
        System.out.println(list.size());
    }

    /**自定義Predicate驗證
     *
     */
    public static void customPridicate(){
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean evaluate(String object) {
                //判斷長度在2-5之間  如果不再返回false
                return object.length()>=2 && object.length()<=5;
            }
        };


        //非空
        Predicate<String> notnull = NotNullPredicate.notNullPredicate();
        //唯一
        Predicate<String> uniquePredicate = UniquePredicate.uniquePredicate();

        //只能放入倆個驗證
        Predicate<String> andPredicate = PredicateUtils.andPredicate(notnull, uniquePredicate);

        //可以放入多個 驗證格式
        Predicate<String> stringPredicate = PredicateUtils.allPredicate(notnull, uniquePredicate, predicate);

        //對於放入的Predicate的順序是有要求的  應該先放入  非空   唯一  長度   根據自己需求來放 為空 和  唯一應該放在最前面
        List<String> list =PredicatedList.predicatedList(new ArrayList<>(),stringPredicate);

        //list.add(null);  java.lang.IllegalArgumentException: Cannot add Object 'null' 
        
        
        list.add("zs");
        //list.add("zs");   java.lang.IllegalArgumentException: Cannot add Object 'zs' - Predicate


        //list.add(" hello word");  Cannot add Object ' hello word'

        list.add("hello");

        list.stream().forEach(System.out::print);
    }


}

Transformer 轉化為指定型別的格式資料

package com.hp.common;


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;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**解耦  將業務處理與判斷進行分離
 *
 */
public class Demo02 {
    public static void main (String[] args) {
        System.out.println("######內建型別轉換 把long型別的資料  轉化為指定型別的時間格式");
        setTransformer();


        System.out.println("######自定義型別轉化");

        Predicate<Staff> predicate = new Predicate<Staff>() {
            @Override
            public boolean evaluate(Staff staff) {
                return staff.getMoney()<10000;
            }
        };


        Predicate<Staff> predicate1 = new Predicate<Staff>() {
            @Override
            public boolean evaluate(Staff staff) {
                return staff.getMoney()>10000;
            }
        };


        Predicate[] predicates={predicate,predicate1};
        //轉化
        Transformer<Staff, Grade> transformer = new Transformer<Staff, Grade>() {
            @Override
            public Grade transform(Staff staff) {
                return new Grade(staff.getName(),"賣身中");
            }
        };


        //轉化
        Transformer<Staff, Grade> transformer1 = new Transformer<Staff, Grade>() {
            @Override
            public Grade transform(Staff staff) {
                return new Grade(staff.getName(),"養身中");
            }
        };
        Transformer[] transformers={transformer,transformer1};
        //將倆者進行關聯
        SwitchTransformer switchTransformer = new SwitchTransformer(predicates, transformers, null);

        //建立容器
        List<Staff> list=new ArrayList<>();
        list.add(new Staff("zs",10000000));
        list.add(new Staff("lisi",2000));


        Collection<Grade> collect = CollectionUtils.collect(list, switchTransformer);

        collect.stream().forEach(System.out::println);


    }

    public static void setTransformer(){
        Transformer<Long, String> transformer = new Transformer<Long, String>() {
            @Override
            public String transform(Long s) {
                return new SimpleDateFormat("yyyy年MM月dd日").format(s);
            }
        };
        ArrayList<Long> list = new ArrayList<>();
        list.add(99999999999L);
        list.add(33333333333333L);
        //CollectionUtils 把倆個關係連線了起來
        Collection<String> collect = CollectionUtils.collect(list, transformer);
        collect.stream().forEach(e-> System.out.println(e));
    }


    //員工類
    static class Staff{
        private String name;
        private int money;

        @Override
        public String toString() {
            return "staff{" +
                    "name='" + name + '\'' +
                    ", money=" + money +
                    '}';
        }
        public Staff(){

        }

        public Staff(String name, int money) {
            this.name = name;
            this.money = money;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getMoney() {
            return money;
        }

        public void setMoney(int money) {
            this.money = money;
        }
    }

    //等級類
    static class Grade{
        private String name;
        private String rank;

        public Grade(){

        }
        public Grade(String name, String rank) {
            this.name = name;
            this.rank = rank;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getRank() {
            return rank;
        }

        public void setRank(String rank) {
            this.rank = rank;
        }

        @Override
        public String toString() {
            return "Grade{" +
                    "name='" + name + '\'' +
                    ", rank='" + rank + '\'' +
                    '}';
        }
    }
}