Apache Commons

Predicate
将判断和容器解耦

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.evaluate(值);
 * 2.NotNullPredicate.INSTANCE
 * 3.UniquePredicate.uniquePredicate()
 * 4.PredicateXxx.predicateXxx(容器  ,判断)
 * 5.自定义判断
 * new Predicate 重写evaluate
 * PredicateUtils.allPredicate-->可以两个以上 andPredicate-->两个 anyPredicate-->只要其中一个为true就为true
 * @author Matrix42
 *
 */
public class Demo01 {

    public static void main(String[] args) {
        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("lorinda");
        //list.add(null);
        //list.add("ll");

    }

    //判断唯一
    public static void unique(){
        System.out.println("======唯一性判断======");
        Predicate<Long> uniquPre = UniquePredicate.uniquePredicate();
        List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(), uniquPre);
        list.add(100L);
        list.add(200L);
        list.add(100L); //出现重复值,出现异常
    }

    //判断非空
    public static void notNull(){
        System.out.println("======非空判断======");
        //Predicate notNull = NotNullPredicate.INSTANCE;
        Predicate notNull = NotNullPredicate.notNullPredicate();
        String str = "lor";
        System.out.println(notNull.evaluate(str));

        //添加容器值的判断
        List<Long> list = PredicatedList.predicatedList(new ArrayList<Long>(), notNull);
        list.add(1000L);
        list.add(null); //验证失败,出现异常
    }

    //相等判断
    public static void equals(){
        System.out.println("======相等判断======");
        Predicate<String>  pre = EqualPredicate.equalPredicate("Matrix42");
        boolean flag = pre.evaluate("lorinda");
        System.out.println(flag);
    }

}

Transformer
类型转换

/**
 * 员工类
 * @author Matrix42
 *
 */
public class Employee {
    private String name;
    private double salary;

    public Employee() {
        // TODO Auto-generated constructor stub
    }

    //Alt + Shift + S + O
    public Employee(String name, double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }
    //Alt+Shift+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() {
        // TODO Auto-generated method stub
        return "(码农:+"+this.name+"敲砖钱:"+this.salary+")";
    }

}
/**
 * 等级类
 * @author Matrix42
 *
 */
public class Level {
    private String name;
    private String level;

    public Level() {
        // TODO Auto-generated constructor stub
    }

    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() {
        // TODO Auto-generated method stub
        return "(码农:"+this.name+",水平:"+this.level+")";
    }
}
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
 * 2.SwitchTransformer
 * CollectionUtils.collect(容器,转换器)
 * @author Matrix42
 *
 */
public class Demo02 {

    public static void main(String[] args) {
        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;
            }

        };

        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> highlowTrans = new Transformer<Employee, Level>() {

            @Override
            public Level transform(Employee input) {
                return new Level(input.getName(),"养身中");
            }
        };

        Transformer[] trans = {lowTrans,highlowTrans};

        //二者进行了关联
        Transformer switchTrans = new SwitchTransformer(pres, trans, null);

        List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee("老马",1000000));
        list.add(new Employee("老裴",9999));

        Collection<Level> levelList = CollectionUtils.collect(list, switchTrans);

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

    /**
     * 内置类型的转换
     */
    public static void inner(){
        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(9999999999999L);
        list.add(3000000000000L);

        Collection<String> result = CollectionUtils.collect(list, trans);

        for (String string : result) {
            System.out.println(string);
        }
    }

}

Goods类:

public class Goods {
    private String name;
    private double price;
    private boolean discount;

    Goods(){

    }

    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 "Goods [name=" + name + ", price=" + price + ", discount="
                + discount + "]";
    }
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

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

import com.google.common.base.Predicate;

/**
 * 函数式编程Closure 闭包 封装特定的业务功能
 * 1.Closure
 * 2.IfClosure IfClosure.ifClosure(断言,功能1,功能2)
 * 3.WhileClosure WhileClosure.whileClosure(断言,功能,标识)
 * 4.ChainedClosure.chainedClosure(功能列表)
 * @author Matrix42
 *
 */
public class Demo03 {

    public static void main(String[] args) {
        basic();
        ifClosure();
        whileClosure();
        chainClosure();
    }

    /**
     * 折上折,先打折,满百再减20
     */
    public static void chainClosure(){
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(new Goods("javase视频",120,true));
        goodsList.add(new Goods("javaee视频",100,false));
        goodsList.add(new Goods("高新技术视频",80,true));

        //满百减二十
        Closure<Goods> subtract = new Closure<Goods>() {

            @Override
            public void execute(Goods input) {
                if(input.getPrice()>=100)
                input.setPrice(input.getPrice()-20);   
            }
        };

        //打折
        Closure<Goods> discount = new Closure<Goods>() {

            @Override
            public void execute(Goods input) {
                if(input.isDiscount()){
                    input.setPrice(input.getPrice()*0.9);  
                }
            }
        };

        //链式操作
        Closure<Goods> ifClo = ChainedClosure.chainedClosure(discount,subtract);
        IterableUtils.forEach(goodsList, ifClo);
        Iterator<Goods> iterator = goodsList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
    /**
     * 确保所有的员工工资都大于10000,如果已经超过的不再上涨
     */
    public static void whileClosure(){
        List<Employee> emplist = new ArrayList<Employee>();
        emplist.add(new Employee("matrix",20000));
        emplist.add(new Employee("lorinda",30000));
        emplist.add(new Employee("sola",15000));

        //业务功能
        Closure<Employee> clos = new Closure<Employee>() {

            @Override
            public void execute(Employee input) {
                input.setSalary(input.getSalary()*1.2);
            }
        };
        //false表示while先判断后执行,true先执行后判断
        Predicate<Employee> empPredicate = new Predicate<Employee>() {

            @Override
            public boolean apply(Employee input) {
                return input.getSalary()<10000;
            }
        };
      //有点问题
        Closure<Employee> whileClos = WhileClosure.whileClosure(empPredicate, clos,false);

        //工具类
        IterableUtils.forEach(emplist, clos);

        //操作后的数据
        Iterator<Employee> empIterator = emplist.iterator();
        while(empIterator.hasNext()){
            System.out.println(empIterator.next());
        }
    }

    /**
     * 二选一,如果是打折商品,进行9折,否则满百减20
     */

    public static void ifClosure(){
        List<Goods> goodsList = new ArrayList<>();
        goodsList.add(new Goods("javase视频",120,true));
        goodsList.add(new Goods("javaee视频",100,false));
        goodsList.add(new Goods("高新技术视频",80,true));

        //满百减二十
        Closure<Goods> subtract = new Closure<Goods>() {

            @Override
            public void execute(Goods input) {
                if(input.getPrice()>=100)
                input.setPrice(input.getPrice()-20);   
            }
        };

        //打折
        Closure<Goods> discount = new Closure<Goods>() {

            @Override
            public void execute(Goods input) {
                if(input.isDiscount()){
                    input.setPrice(input.getPrice()*0.9);  
                }
            }
        };

        //判断
        Predicate<Goods> predicate = new Predicate<Goods>() {

            @Override
            public boolean apply(Goods input) {
                return input.isDiscount();
            }
        };

        //二选一
        //有点问题
        Closure<Goods> ifClo = IfClosure.ifClosure(predicate, discount, subtract);
        IterableUtils.forEach(goodsList, ifClo);
        Iterator<Goods> iterator = goodsList.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }

    public static void basic(){
        List<Employee> emplist = new ArrayList<Employee>();
        emplist.add(new Employee("matrix",20000));
        emplist.add(new Employee("lorinda",30000));
        emplist.add(new Employee("sola",15000));

        //业务功能
        Closure<Employee> clos = new Closure<Employee>() {

            @Override
            public void execute(Employee input) {
                input.setSalary(input.getSalary()*1.2);
            }
        };

        //工具类
        IterableUtils.forEach(emplist, clos);

        //操作后的数据
        Iterator<Employee> empIterator = emplist.iterator();
        while(empIterator.hasNext()){
            System.out.println(empIterator.next());
        }

    }

}
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;

/**
 * 集合操作
 * 1.并集
 * CollectionUtils.union
 * 2.交集
 * CollectionUtils.intersection
 * CollectionUtils.retainAll
 * 3.差集
 * CollectionUtils.subtract
 * @author Matrix42
 *
 */
public class Demo04 {

    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<Integer>();
        set1.add(1);
        set1.add(2);
        set1.add(3);
        Set<Integer> set2 = new HashSet<Integer>();
        set2.add(2);
        set2.add(3);
        set2.add(4);

        //并集
        System.out.println("======并集======");
        Collection<Integer> collection = CollectionUtils.union(set1, set2);
        for (Integer integer : collection) {
            System.out.println(integer);
        }

        //交集
        System.out.println("======交集======");
        collection = CollectionUtils.retainAll(set1, set2);
        for (Integer integer : collection) {
            System.out.println(integer);
        }

      //交集
        System.out.println("======交集======");
        collection = CollectionUtils.subtract(set1, set2);
        for (Integer integer : collection) {
            System.out.println(integer);
        }   
    }
}
import java.util.Queue;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.functors.NotNullPredicate;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.collections4.queue.PredicatedQueue;
import org.apache.commons.collections4.queue.UnmodifiableQueue;

/**
 * Queue队列
 * 1.循环队列
 * 2.只读队列:不可改变队列
 * @author Matrix42
 *
 */
public class Demo05 {

    public static void main(String[] args) {
        circular();
        readOnly();
        predicate();
    }

    /**
     * 断言队列
     */
    public static void predicate(){
        CircularFifoQueue<String> queue = new CircularFifoQueue<String>(2);
        queue.add("a");
        queue.add("b");
        queue.add("c");
        Predicate notNull = NotNullPredicate.INSTANCE;
        Queue<String> queue2 = PredicatedQueue.predicatedQueue(queue,notNull);
        queue.add(null);

    }

    /**
     * 只读队列
     */
    public static void readOnly(){
        CircularFifoQueue<String> queue = new CircularFifoQueue<String>(2);
        queue.add("a");
        queue.add("b");
        queue.add("c");

        Queue<String> readOnlyQueue = UnmodifiableQueue.unmodifiableQueue(queue);
        readOnlyQueue.add("d");

    }

    /**
     * 循环队列
     */
    public static void circular(){
        CircularFifoQueue<String> queue = new CircularFifoQueue<String>(2);
        queue.add("a");
        queue.add("b");
        queue.add("c");

        for(int i=0;i<queue.size();i++){
            System.out.println(queue.get(i));
        }
    }

}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.iterators.ArrayListIterator;
import org.apache.commons.collections4.iterators.FilterIterator;
import org.apache.commons.collections4.iterators.LoopingIterator;
import org.apache.commons.collections4.iterators.UniqueFilterIterator;
import org.apache.commons.collections4.map.HashedMap;

/**
 迭代器的扩展
 1、MapIterator 以后不再使用map.keySet.iterator访问
  IterableMap  HashedMap
 2、UniqueFilterIterator 去重迭代器 
 3、FilterIterator 自定义过滤 +Predicate
 4、LoopingIterator 循环迭代器
 5、ArrayListIterator 数组迭代器
 *
 */
public class Demo06 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        //mapIt();
        //uniqueIt();
        //filterIt();
        //loopIt();
        arrayIt();
    }
    /**
     * 数组迭代器
     */
    public static void arrayIt(){
        System.out.println("===== 数组迭代器  ====");
        int[] arr ={1,2,3,4,5};
        //数组迭代器
        //Iterator<Integer> it =new ArrayListIterator<Integer>(arr);
        //指定起始索引和结束索引
        Iterator<Integer> it =new ArrayListIterator<Integer>(arr,1,3);
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
    /**
     * 循环迭代器
     */
    public static void loopIt(){
        System.out.println("===== 循环迭代器  ====");
        List<String> list =new ArrayList<String>();
        list.add("refer");
        list.add("dad");
        list.add("bjsxt");
        list.add("moom");

        Iterator<String> it =new LoopingIterator(list);
        for(int i=0;i<15;i++){
            System.out.println(it.next());
        }
    }
    /**
     * 自定义迭代器 
     */
    public static void filterIt(){
        System.out.println("=====自定义迭代器  ====");
        List<String> list =new ArrayList<String>();
        list.add("refer");
        list.add("dad");
        list.add("lorinda");
        list.add("moom");
        //自定义条件判断
        Predicate<String> pre =new Predicate<String>(){
            public boolean evaluate(String value) {
                //回文判断
                return new StringBuilder(value).reverse().toString().equals(value);
            }};

        //去除重复的过滤器
        Iterator<String> it =new FilterIterator(list.iterator(),pre);
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
    /**
     * 去重迭代器 
     */
    public static void uniqueIt(){
        System.out.println("=====去重迭代器 ====");
        List<String> list =new ArrayList<String>();
        list.add("a");
        list.add("b");
        list.add("a");
        //去除重复的过滤器
        Iterator<String> it =new UniqueFilterIterator(list.iterator());
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }
    /**
     * map迭代器
     */
    public static void mapIt(){
        System.out.println("=====map迭代器====");
        IterableMap<String,String> map =new HashedMap<String,String>();
        map.put("a","lorinda");
        map.put("b", "asd");
        map.put("c", "good");
        //使用 MapIterator
        MapIterator<String,String> it =map.mapIterator();
        while(it.hasNext()){
            //一定要it.next() 
            /*
            it.next();
            String key =it.getKey();
            */
            String key =it.next();
            String value =it.getValue();
            System.out.println(key+"-->"+value);
        }
    }
}
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;
import org.apache.commons.collections4.bidimap.DualTreeBidiMap;

/**
 双向Map 要求键与值都不能重复
 BidiMap  inverseBidiMap()
 1、DualTreeBidiMap :有序
 2、DualHashBidiMap :无序
 *
 */
public class Demo07 {

    public static void main(String[] args) {
        //hashMap();
        treeMap();
    }
    /**
     * 有序的双向Map
     */
    public static void treeMap(){
        System.out.println("=====有序的双向Map====");
        BidiMap<String,String> map =new DualTreeBidiMap<String,String>();
        map.put("bj", "bj@test.com");
        map.put("oiuo", "qwe@qq.com");  
        //遍历查看
        MapIterator<String,String> it =map.inverseBidiMap().mapIterator();
        while(it.hasNext()){
            String key =it.next();
            String value =it.getValue();
            System.out.println(key+"-->"+value);
        }
    }

    /**
     * 无序的双向Map
     */
    public static void hashMap(){
        System.out.println("=====无序的双向Map====");
        BidiMap<String,String> map =new DualHashBidiMap<String,String>();
        map.put("bj", "bj@test.com");
        map.put("lol", "ioi@qq.com");
        //反转
        System.out.println(map.inverseBidiMap().get("sxt@qq.com"));
        //遍历查看
        MapIterator<String,String> it =map.inverseBidiMap().mapIterator();
        while(it.hasNext()){
            String key =it.next();
            String value =it.getValue();
            System.out.println(key+"-->"+value);
        }
    }
}
import java.util.Iterator;
import java.util.Set;

import org.apache.commons.collections4.Bag;
import org.apache.commons.collections4.bag.HashBag;
import org.apache.commons.collections4.bag.TreeBag;

/**
 Bag 包 允许重复
 1、HashBag 无序
 2、TreeBag 有序
 统计单词的出现次数
 *
 */
public class Demo08 {

    public static void main(String[] args) {
        //hashBag();
        //treeBag();
        String str ="this is a cat and that is a mice where is the food";
        //分割字符串
        String[] strArray =str.split(" ");
        Bag<String> bag =new TreeBag<String>();
        for(String temp:strArray){
            bag.add(temp);
        }

        System.out.println("====统计次数===");
        Set<String> keys =bag.uniqueSet();
        for(String letter:keys){
            System.out.println(letter+"-->"+bag.getCount(letter));
        }

    }
    /**
     * 有序
     */
    public static void treeBag(){
        System.out.println("=====有序的包====");
        Bag<String> bag =new TreeBag<String>();
        bag.add("a");
        bag.add("a",5);
        bag.remove("a", 2);
        bag.add("b");
        bag.add("c");
        Iterator<String> it =bag.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }

    /**
     * 无序
     */
    public static void hashBag(){
        System.out.println("=====无序的包====");
        Bag<String> bag =new HashBag<String>();
        bag.add("a");
        bag.add("a",5);
        bag.remove("a", 2);
        bag.add("b");
        bag.add("c");
        Iterator<String> it =bag.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
    }

}