java基础--extension package commons(3)

 1. apache commons 类库详解

一、Commons BeanUtils
        说明:针对Bean的一个工具集。由于Bean往往是有一堆get和set组成,所以BeanUtils也是在此基础上进行一些包装。

   Commons BeanUtils一共包括如下5个包:

           org.apache.commons.beanutils – 核心包,定义一组Utils类和需要用到的接口规范

          org.apache.commons.beanutils.converters – 转换String到需要类型的类,实现Converter接口

          org.apache.commons.beanutils.locale – beanutils的locale敏感版本

          org.apache.commons.beanutils.locale.converters – converters的locale敏感版本

          org.apache.commons.collections – beanutils使用到的Collection类

二、Commons CLI
说明:这是一个处理命令的工具。比如main方法输入的string[]需要解析。你可以预先定义好参数的规则,然后就可以调用CLI来解析。

三、Commons Codec
说明:这个工具是用来编码和解码的,包括Base64,URL,Soundx等等。用这个工具的人应该很清楚这些,我就不多介绍了。

四、Commons Collections
说明:你可以把这个工具看成是java.util的扩展。

   Packages 
      org.apache.commons.collections 
     org.apache.commons.collections.bag 
     org.apache.commons.collections.bidimap 
     org.apache.commons.collections.buffer 
     org.apache.commons.collections.collection 
    org.apache.commons.collections.comparators 
    org.apache.commons.collections.functors 
    org.apache.commons.collections.iterators 
    org.apache.commons.collections.keyvalue 
    org.apache.commons.collections.list 
    org.apache.commons.collections.map 
    org.apache.commons.collections.set 

五、Commons Configuration
      说明:这个工具是用来帮助处理配置文件的,支持很多种存储方式

六、Commons DBCP
说明:Database Connection pool, Tomcat就是用的这个,不用我多说了吧,要用的自己去网站上看说明。

 七、Commons DbUtils
说明:我以前在写数据库程序的时候,往往把数据库操作单独做一个包。DbUtils就是这样一个工具,以后开发不用再重复这样的工作了。值得一体的是,这个工具并不是现在流行的OR-Mapping工具(比如Hibernate),只是简化数据库操作

    1、Commons FileUpload
     说明:jsp的上传文件功能怎么做呢?

八、Commons HttpClient
     说明:这个工具可以方便通过编程的方式去访问网站。

九、Commons IO
说明:可以看成是java.io的扩展,我觉得用起来非常方便。

十、Commons JXPath
说明:Xpath你知道吧,那么JXpath就是基于Java对象的Xpath,也就是用Xpath对Java对象进行查询。这个东西还是很有想像力的。

 十一、Commons Lang
说明:这个工具包可以看成是对java.lang的扩展。提供了诸如StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils等工具类。

十二、Commons Logging
说明:你知道Log4j吗?

十三、Commons Math
说明:看名字你就应该知道这个包是用来干嘛的了吧。这个包提供的功能有些和Commons Lang重复了,但是这个包更专注于做数学工具,功能更强大。

十四、Commons Net
说明:这个包还是很实用的,封装了很多网络协议。

      1. FTP   2. NNTP  3. SMTP  4. POP3   5. Telnet  6. TFTP  7. Finger  8. Whois  9. rexec/rcmd/rlogin  10. Time (rdate) and Daytime  11. Echo  12. Discard    13. NTP/SNTP

十五、Commons Validator
说明:用来帮助进行验证的工具。比如验证Email字符串,日期字符串等是否合法。
十六、Commons Virtual File System
说明:提供对各种资源的访问接口。支持的资源类型包括
1. CIFS   2. FTP  3. Local Files    4. HTTP and HTTPS    5. SFTP    6. Temporary Files     7. WebDAV    8. Zip, Jar and Tar (uncompressed, tgz or tbz2)   9. gzip and bzip2   10. res   11. ram
十七、Commons Transaction
     说明:提供持久层事务支持

十八、Commons pool
说明: 创建新的对象并初始化的操作,可能会消耗很多的时间。
在需要频繁创建并使用这些对象的场景中,为了提供系统性能,通常的做法是,创建一个对象池,将一定数量的对象缓存到这个对象池中。
需要使用时直接从对象池中取出对象,使用完后将对象扔回到对象池中即可。
Apache的commons pool组件是我们实现对象池化技术的良好助手。

十九、Commons Launcher
说明:创建跨平台可执行程序
二十、Commons Bean Scripting Framework(BSF)
说明:是一个支持在Java应用程序内调用脚本语言 (Script),并且支持脚本语言直接访问Java对象和方法的一个开源项目。有了它 , 你就能在java application中使用javascript, Python, XSLT, Perl, tcl, ……等一大堆scripting language
. 反过来也可以,就是在这些scripting language中调用任何已经注册过了的JavaBean,java object。它提供了完整的API实现通过Java访问脚本语言的引擎。
二十一、Commons chain
说明: 可以在你需要定义和执行一些顺序操作的时候采用Commons Chain。

二十二、Commons Compress
说明: 是一个压缩、解压缩文件的类库。可以操作ar, cpio, Unix dump, tar, zip, gzip, XZ, Pack200 and bzip2格式的文件,功能比较强大

二十三、Commons Discovery
说明: 组件被用以查找可插拔接口的实现实例,它提供了一种通用的实例化这些实现的方式,而且可以管理单例(工厂)的生命周期。

 二十四、 commons exec
说明: Apache Commons Exec 是 Apache 上的一个 Java 项目,提供一些常用的方法用来执行外部进程,

二十五、commons jelly
说明:Jelly能够把XML转换成可执行代码,所以Jelly是一个基于XML与Java的脚本和处理引擎。 Jelly借鉴了JSP定指标签,Velocity, Cocoon和Xdoclet中的脚本引擎的许多优点。Jelly可以用在命令行,Ant或者Servlet之中

2、Commons Collections  代码区

package com.zwj.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 
  3、UniquePredicate.uniquePredicate()
  4、自定义
     new Predicate() +evaluate  
    PredicateUtils.allPredicate  andPredicate anyPredicate
    PredicatedXxx.predicatedXxx(容器,判断)
 * @author Administrator
 *
 */
public class Demo01 {

    /**
     * @param args
     *  定义 List<String>  集合添加字符串长度  大于5
     */
    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(notNull,selfPre);
        
        List<String> list =PredicatedList.predicatedList(new ArrayList<String>(),all);
        list.add("bjsxt");
        list.add("bjstrew");
        /*list.add(null);
        list.add("bj");    */
        Demo01.equal();
        
    }
    /**
     * 判断唯一
     */
    public static void unique(){
        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 notNull(){
        System.out.println("====非空判断====");
        //Predicate notNull=NotNullPredicate.INSTANCE;
        Predicate 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); //验证失败,出现异常
    }
    
    
    /**
     * 比较相等判断
     */
    public static void equal(){
        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);
    }

}
Demo01 函数式编程 之 Predicate
package com.zwj.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
 2、SwitchTransformer
 CollectionUtils.collect(容器,转换器)
 * @author Administrator
 *
 */
public class Demo02 {

    /**
     * @param args
     */
    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> highTrans =new Transformer<Employee,Level>(){

            @Override
            public Level transform(Employee input) {
                return new Level(input.getName(),"养身中");
            }};
        Transformer[] trans ={lowTrans,highTrans};    
        
        //二者进行了关联
        Transformer switchTrans =new SwitchTransformer(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());
        }
/*===自定义类型转换==
(码农:老马,水平:养身中)
(码农:老裴,水平:卖身中)
*/        inner();
    }
    /**
     * 内置类型的转换
     */
    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(999999999999L);
        list.add(300000000L);
        
        //工具类 程序猿出钱---开发商---农民工出力
        Collection<String>  result=CollectionUtils.collect(list, trans);
        //遍历查看结果
        for(String time:result){
            System.out.println(time);
        }
    }

}
/*===内置类型转换  长整形时间日期,转成指定格式的字符串==
2001年09月09日
1970年01月04日
*/
Demo02 函数式编程 Transformer 类型转化
package com.zwj.commons;
/**
 * 员工类
 * @author Administrator
 *
 */
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+")";
    }
    
}
Employee demo2实体类
package com.zwj.commons;
/**
 * 等级类
 * @author Administrator
 *
 */
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() {
        return "(码农:"+this.name+",水平:"+this.level+")";
    }
}
Level demo2实体类
package com.zwj.commons;
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(容器,功能类对象);
 * @author Administrator
 *
 */
public class Demo03 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        basic();        
        //ifClosure();
        //whileClosure();
        //chainClosure();
    }
    /**
     * 折上减   先打折商品,进行9折,满百再减20
     */
    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> chainClo=ChainedClosure.chainedClosure(discount,subtract);
        
        //关联
        CollectionUtils.forAllDo(goodsList,chainClo);
        
        //查看操作后的数据
        for(Goods temp:goodsList){
            System.out.println(temp);
        }
/*(商品:javase视频,价格:88.0,是否打折:是)
(商品:javaee视频,价格:80.0,是否打折:否)
(商品:高新技术视频,价格:80.0,是否打折:否)
*/        
    }
    
    /**
     * 确保所有的员工工资都大于10000,如果已经超过的不再上涨
     */
    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> cols=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> whileCols =WhileClosure.whileClosure(empPre, cols, false);
            
        //工具类
        CollectionUtils.forAllDo(empList, whileCols)    ;
        
        //操作后的数据
        Iterator<Employee> empIt=empList.iterator();
        while(empIt.hasNext()){
            System.out.println(empIt.next());
        }
/*(码农:bjsxt,敲砖钱:20000.0)
(码农:is,敲砖钱:10000.0)
(码农:good,敲砖钱:10368.0)*/
    }
    /**
     * 二选一  如果是打折商品,进行9折,否则满百减20
     */
    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> ifClo=IfClosure.ifClosure(pre, discount,subtract);
        
        //关联
        CollectionUtils.forAllDo(goodsList,ifClo);
        
        //查看操作后的数据
        for(Goods temp:goodsList){
            System.out.println(temp);
        }
/*(商品:javase视频,价格:108.0,是否打折:是)
(商品:javaee视频,价格:80.0,是否打折:否)
(商品:高新技术视频,价格:80.0,是否打折:否)*/        
    }
    /**
     * 基本操作
     */
    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> cols=new Closure<Employee>(){
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary()*1.2);
            }};
        
        //工具类
        CollectionUtils.forAllDo(empList, cols)    ;
        
        //操作后的数据
        Iterator<Employee> empIt=empList.iterator();
        while(empIt.hasNext()){
            System.out.println(empIt.next());
        }
    }

}
/*(码农:bjsxt,敲砖钱:24000.0)
(码农:is,敲砖钱:12000.0)
(码农:good,敲砖钱:6000.0)
*/
Demo03 函数式编程 Closure 闭包 封装特定的业务功能
package com.zwj.commons;
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 Administrator
 *
 */
public class Demo04 {

    /**
     * @param args
     */
    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> col =CollectionUtils.union(set1,set2);
        for(Integer temp:col){
            System.out.println(temp);
        }
        //交集
        System.out.println("=========交集============");               
        //col =CollectionUtils.intersection(set1, set2);
        col =CollectionUtils.retainAll(set1, set2);
        for(Integer temp:col){
            System.out.println(temp);
        }
        //差集
        System.out.println("=========差集============");       
        col =CollectionUtils.subtract(set1, set2);
        for(Integer temp:col){
            System.out.println(temp);
        }        
    }

}
Demo04 集合操作 并集、交集
package com.zwj.commons;

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、循环队列:CircularFifoQueue
 2、只读队列:不可改变队列  UnmodifiableQueue
 3、断言队列:PredicatedQueue.predicatedQueue()
 * @author Administrator
 *
 */
public class Demo05 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        /*circular();
        readOnly();*/
        predicate();
    }
    /**
     * 断言队列
     */
    public static void predicate(){
        //循环队列
        CircularFifoQueue<String> que =new CircularFifoQueue<String>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        Predicate notNull=NotNullPredicate.INSTANCE;
        //包装成对应的队列
        Queue<String> que2=PredicatedQueue.predicatedQueue(que, notNull);
        que2.add("e");
        for(int i=0;i<que.size();i++){
            System.out.println(que.get(i));
/*
 c
e*/        }
    }
    /**
     * 只读队列
     */
    public static void readOnly(){
        //循环队列
        CircularFifoQueue<String> que =new CircularFifoQueue<String>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        Queue<String> readOnlyQue =UnmodifiableQueue.unmodifiableQueue(que);
        readOnlyQue.add("d");//只能读取
    }
    /**
     * 循环队列
     */
    public static void circular(){
        //循环队列
        CircularFifoQueue<String> que =new CircularFifoQueue<String>(2);
        que.add("a");//容器只有2个  c的加入把a挤出去了
        que.add("b");
        que.add("c");
        //查看
        for(int i=0;i<que.size();i++){
            System.out.println(que.get(i));
        }
        
    }

}
Demo05 Queue队列
package com.zwj.commons;
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 数组迭代器
 * @author Administrator
 *
 */
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);
        //指定起始索引和结束索引  1
        Iterator<Integer> it =new ArrayListIterator<Integer>(arr,1,3);
        while(it.hasNext()){
            System.out.println(it.next());
        }
/*c
  e*/        
    }
    /**
     * 循环迭代器
     */
    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());
        }
/*===== 循环迭代器  ====
refer
dad
bjsxt
moom
refer
dad
bjsxt
moom
refer
dad
bjsxt
moom
refer
dad
bjsxt*/    }
    /**
     * 自定义迭代器 
     */
    public static void filterIt(){
        System.out.println("=====自定义迭代器  ====");
        List<String> list =new ArrayList<String>();
        list.add("refer");
        list.add("dad");
        list.add("bjsxt");
        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());
        }
        /*=====自定义迭代器  ====
        refer
        dad
        moom
        */    }
    /**
     * 去重迭代器 
     */
    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","bjsxt");
        map.put("b", "sxt");
        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);
        }
        
        
    }
/*=====map迭代器====
a-->bjsxt
c-->good
b-->sxt*/
}
Demo06 迭代器的扩展
package com.zwj.commons;
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;

/**
 
 BidiMap  inverseBidiMap()
 1、DualTreeBidiMap :有序
 2、DualHashBidiMap :无序
 * @author Administrator
 *
 */
public class Demo07 {

    /**
     * @param args
     */
    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("sxt", "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);
        }
/*=====有序的双向Map====
bj@test.com-->bj
sxt@qq.com-->sxt*/    }

    /**
     * 无序的双向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("sxt", "sxt@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);
        }
    }

/*
 =====无序的双向Map====
sxt
sxt@qq.com-->sxt
bj@test.com-->bj
*/}
Demo07 双向Map 要求键与值都不能重复
package com.zwj.commons;
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 有序
 统计单词的出现次数
 * @author Administrator
 *
 */
public class Demo08 {

    /**
     * @param args
     */
    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));
        }
        Demo08.hashBag();
    }
    /**
     * 有序
     */
    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());
        }
/*=====有序的包====
a
a
a
a
b
c*/}

    /**
     * 无序
     */
    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());
        }
    }

}
/*=====无序的包====
b
c
a
a
a
a*/
Demo08 Bag 包 允许重复
package com.zwj.commons;
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?"是":"否")+")";
    }
    
    
}
Goods demo3实体类
原文地址:https://www.cnblogs.com/ou-pc/p/7859933.html