程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> Apache Commons Collections基本操作(Predicate、Transformat、Closure等)

Apache Commons Collections基本操作(Predicate、Transformat、Closure等)

編輯:C++入門知識

Apache Commons Collections基本操作(Predicate、Transformat、Closure等)


一、Predicate斷言

package Collections;

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.notNullPredicate
 *     NotNullPredicate.INSTANCE
 *     
 *     PredicatedList.predicatedXxx(容器,判斷)
 *     
 *  3、 UniquePredicate.uniquePredicate()
 *  
 *  4、 自定義  new Predicate類 + 重寫evaluate方法
 *          PredicateUtils.allPredicate   多於兩個
 *                         andPredicate   兩個
 *                         anyPredicate   其中一個
 *        
 */
@SuppressWarnings("all")
public class Demo01 {
    public static void main(String[] args) {
        Test001();
        Test002();
        Test003();
        Test004();      
    }

    /**
     * 比較相等判斷
     */
   public static void Test001()
   {
        System.out.println("=====相等判斷=======");
        Predicate pre = new EqualPredicate("liguodong");
        //Predicate pre = EqualPredicate.equalPredicate("liguodong");//同上
        boolean flag = pre.evaluate("li");
        System.out.println(flag);       
   }


   /**
    * 非空判斷
    */
   public static void Test002()
   {
        System.out.println("=====非空判斷=======");
        Predicate  notNull = NotNullPredicate.INSTANCE;
        //Predicate  notNull = NotNullPredicate.notNullPredicate();//同上
        String str = "lgd";
        System.out.println(notNull.evaluate(str));//非空為true,否則為false。

        //添加容器值得判斷
        List list = PredicatedList.predicatedList(new ArrayList<>(), notNull);
        list.add(1000L);
        //list.add(null);//null值為false, 驗證失敗,出現異常
   }


   public static void Test003()
    {
        System.out.println("=====唯一性判斷=======");
        Predicate uniquePre = UniquePredicate.uniquePredicate();      
        List list = PredicatedList.predicatedList(new ArrayList(),uniquePre);
        list.add(100L);
        list.add(200L);
        //list.add(100L);//出現重復值,拋出異常

    }


   public static void Test004(){
       System.out.println("=====自定義判斷=======");
        //自定義的判別式
        Predicate selfPre = new Predicate() {
            @Override
            public boolean evaluate(String object) {
                return object.length()>=5&&object.length()<=20;
            }       
        };

        Predicate notNull = NotNullPredicate.notNullPredicate();//非空

        Predicate all = PredicateUtils.allPredicate(selfPre,notNull);       
        List list = PredicatedList.predicatedList(new ArrayList<>(), all);
        list.add("liguodong");
        //list.add(null);//java.lang.NullPointerException
        //list.add("byby");//java.lang.IllegalArgumentException
   }
}

運行結果:

=====相等判斷=======
false
=====非空判斷=======
true
=====唯一性判斷=======
=====自定義判斷=======

二、Transformat 類型轉換

package Collections;
/**
 * 員工類
 */
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+")";
    }

}
package Collections;

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+")";
    }
}
package Collections;

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;

/**
 * 解耦:將 業務處理與判斷進行分離
 * 
 * 函數式編程Transformat 類型轉換
 * 1.Transformer+CollectionUtils.collect
 * 
 * 2.SwitchTransformer
 *   CollectionUtils.collect(容器,轉換器)
 */

@SuppressWarnings("all")
public class Demo02 {   
    public static void main(String[] args) {
        inner();
        define();
    }

    //內置類型的轉化
    public static void inner()
    {
        System.out.println("========《內置類型轉換 長整型時間日期,轉成指定格式的字符串》========");
        //類型轉換器
        Transformer trans = new Transformer()
        {
            @Override
            public String transform(Long input) {
                return new SimpleDateFormat("yyyy年MM月dd日").format(input);
            }

        };

        //容器
        List list = new ArrayList<>();
        list.add(99999999L);
        list.add(30000L);

        //工具類:程序員出錢<---開發商--->農民工出力
        Collection result = CollectionUtils.collect(list, trans);

        //遍歷查看結果
        for(String time:result){
            System.out.println(time);
        }
    }

    //自定義類型轉換
    public static void define(){
        System.out.println("==========《自定義類型轉換》===========");

        Predicate isLow = new Predicate(){
            public boolean evaluate(Employee emp)
            {
                return emp.getSalary()<=10000;
            }
        };              
        Predicate isHigh = new Predicate() {
            public boolean evaluate(Employee emp)
            {
                return emp.getSalary()>=10000;
            }
        };  
        Predicate[] pres = {isLow,isHigh};


        //轉換
        Transformer lowtrans = new Transformer()
        {   
            @Override
            public Level transform(Employee input) {
                return new Level(input.getName(),"低薪");
            }
        };              
        //轉換
        Transformer hightrans = new Transformer()
        {   
            @Override
            public Level transform(Employee input) {
                return new Level(input.getName(),"高薪");
            }
        };      
        Transformer[] trans = {lowtrans,hightrans};


        //二者進行了關聯
        Transformer switchTrans = new SwitchTransformer<>(pres, trans, null);

        List list = new ArrayList<>();
        list.add(new Employee("鳳姐",10000000));
        list.add(new Employee("犀利哥",1000));

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

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

運行結果:

========《內置類型轉換 長整型時間日期,轉成指定格式的字符串》========
1970年01月02日
1970年01月01日
==========《自定義類型轉換》===========
(碼農:鳳姐,水平:高薪)
(碼農:犀利哥,水平:低薪)

三、Closure 閉包封裝業務功能

package Collections;
/**
 * 員工類
 */
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+")";
    }

}
package Collections;

public class Goods {
    private String name;
    private double price;
    private boolean discount;//折扣
    public 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 "(商品:"+this.name+",價格:"+this.price+",是否打折:"+(discount?"是":"否")+")";      
    }
}
package Collections;

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
 *      CollectionUtils.forAllDo(容器,功能類對象)
 *  
 *  2.  IfClosure    
 *      IfClosure.ifClosure(斷言,功能1,功能2)
 *      CollectionUtils.forAllDo(容器,功能類對象)
 *  
 *  3.  WhileClosure
 *      WhileClosure.whileClosure(斷言,功能,標識符)
 *      CollectionUtils.forAllDo(容器,功能類對象)
 *  
 *  4.  ChainedClosure
 *      ChainedClosure.chainedClosure(功能列表)
 *      CollectionUtils.forAllDo(容器,功能類對象)
 * @author liguodong
 */

@SuppressWarnings("all")
public class Demo03 {
    public static void main(String[] args) {
        basic();
        System.out.println("==================");
        ifClousure();
        System.out.println("==================");
        whileClosure();
        System.out.println("==================");
        chainClousure();
    }


    //基本操作
    public static void basic()
    {
        //數據
        List empList = new ArrayList<>();
        empList.add(new Employee("mark",20000));
        empList.add(new Employee("json",10000));
        empList.add(new Employee("Ivy",5000));

        //業務功能
        Closure cols = new Closure()
        {
            @Override
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary()*1.2);
            }

        };

        //工具類
        CollectionUtils.forAllDo(empList, cols);        

        //操作後的數據
        Iterator empIt = empList.iterator();
        while(empIt.hasNext())
        {
            System.out.println(empIt.next());
        }
    }


    /**
     * 二選一  如果打折商品,進行9折;否則滿百減20。
     */
    public static void ifClousure()
    {
        List goodsList = new ArrayList<>();
        goodsList.add(new Goods("android視頻",120,true));
        goodsList.add(new Goods("javaee視頻",80,false));
        goodsList.add(new Goods("hadoop視頻",150,false));

        //滿百減20
        Closure subtract = new Closure() {
            @Override
            public void execute(Goods input) {
                if(input.getPrice()>=100){
                    input.setPrice(input.getPrice()-20);
                }           
            }
        };

        //打折
        Closure discount = new Closure() {
            @Override
            public void execute(Goods input) {
                if(input.isDiscount()){
                    input.setPrice(input.getPrice()*0.9);
                }           
            }
        };

        //判斷
        Predicate pre = new Predicate() {
            @Override
            public boolean evaluate(Goods goods) {
                return goods.isDiscount();
            }
        };

        //二選一
        Closure ifClo = IfClosure.ifClosure(pre,discount,subtract);

        //關聯
        CollectionUtils.forAllDo(goodsList,ifClo);  

        //查看操作後的數據
        for(Goods temp:goodsList)
        {
            System.out.println(temp);
        }
    }



    /**
     * 確保所有的員工工資都大於10000,如果已經超過的不再上漲 。
     */
    public static void whileClosure()
    {
        //數據
        List empList = new ArrayList<>();
        empList.add(new Employee("周傑倫",20000));
        empList.add(new Employee("范冰冰",30000));
        empList.add(new Employee("黃曉明",5000));

        //業務功能 每次上漲0.2
        Closure cols = new Closure()
        {
            @Override
            public void execute(Employee emp) {
                emp.setSalary(emp.getSalary()*1.2);
            }

        };

        //判斷
        Predicate empPre = new Predicate() {
            @Override
            public boolean evaluate(Employee emp) {
                return emp.getSalary()<10000;
            }
        };

        //false 表示while結構先判斷後執行   
        //true  表示do..while先執行後判斷
        Closure whileCols = WhileClosure.whileClosure(empPre,cols,false); 


        //工具類
        CollectionUtils.forAllDo(empList, whileCols);

        //操作後的數據
        Iterator empIt = empList.iterator();
        while(empIt.hasNext())
        {
            System.out.println(empIt.next());
        }
    }   



    /**
     *折上減   如果打折商品,先進行9折,如果還滿百,再減20
     */
    public static void chainClousure()
    {
        List goodsList = new ArrayList<>();
        goodsList.add(new Goods("Android視頻",120,true));
        goodsList.add(new Goods("javaee視頻",100,false));
        goodsList.add(new Goods("Spack視頻",80,false));

        //滿百減20
        Closure subtract = new Closure() {
            @Override
            public void execute(Goods input) {
                if(input.getPrice()>=100){
                    input.setPrice(input.getPrice()-20);
                }
            }
        };

        //打折
        Closure discount = new Closure() {
            @Override
            public void execute(Goods input) {
                if(input.isDiscount()){
                    input.setPrice(input.getPrice()*0.9);
                }           
            }
        };

        //鏈式操作
        Closure chinaClo = ChainedClosure.chainedClosure(discount,subtract);

        //關聯
        CollectionUtils.forAllDo(goodsList,chinaClo);

        //查看操作後的數據
        for(Goods temp:goodsList)
        {
            System.out.println(temp);
        }
    }
}

運行結果:

(碼農:mark,薪水:24000.0)
(碼農:json,薪水:12000.0)
(碼農:Ivy,薪水:6000.0)
==================
(商品:android視頻,價格:108.0,是否打折:是)
(商品:javaee視頻,價格:80.0,是否打折:否)
(商品:hadoop視頻,價格:130.0,是否打折:否)
==================
(碼農:周傑倫,薪水:20000.0)
(碼農:范冰冰,薪水:30000.0)
(碼農:黃曉明,薪水:10368.0)
==================
(商品:Android視頻,價格:88.0,是否打折:是)
(商品:javaee視頻,價格:80.0,是否打折:否)
(商品:Spack視頻,價格:80.0,是否打折:否)

四、集合操作

package Collections;

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
 */
public class Demo04 {
    public static void main(String[] args) {
        Set set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);

        Set set2 = new HashSet<>();
        set2.add(2);
        set2.add(3);
        set2.add(4);
        System.out.println("========並集==========");
        //並集
        Collection col = CollectionUtils.union(set1, set2);
        for(Integer temp:col)
        {
            System.out.print(temp+" ");
        }
        System.out.println("\n=========交集=========");
        //交集
        //col  = CollectionUtils.intersection(set1, set2);
        col  = CollectionUtils.retainAll(set1, set2);
        for(Integer temp:col)
        {
            System.out.print(temp+" ");
        }       
        //差集
        System.out.println("\n=========差集=========");
        col  = CollectionUtils.subtract(set1, set2);
        for(Integer temp:col)
        {
            System.out.print(temp+" ");
        }       
    }
}

運行結果:

========並集==========
1 2 3 4 
=========交集=========
2 3 
=========差集=========
1 

五、Queue隊列

package Collections;

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.只讀隊列:不可改變隊列
 */
@SuppressWarnings("all")
public class Demo05 {
    public static void main(String[] args) {
        circullar();
        readOnly();
        //predicate();
    }

    /**
     * 循環隊列
     */
    public static void circullar()
    {
        //長度是2,因此只能保留兩個,循環著走。
        CircularFifoQueue que = new CircularFifoQueue<>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        que.add("d");
        //查看
        for(int i=0;i que = new CircularFifoQueue<>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        Queue readOnlyOne = UnmodifiableQueue.unmodifiableQueue(que);
        //readOnlyOne.add("d");//java.lang.UnsupportedOperationException
    }

    /**
     * 斷言隊列
     */
    public static void predicate()
    {
        //循環隊列
        CircularFifoQueue que = new CircularFifoQueue<>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        Predicate notNull = NotNullPredicate.INSTANCE;
        //包裝成對應的隊列
        Queue que2 = PredicatedQueue.predicatedQueue(que,notNull);
        //que2.add(null);//java.lang.IllegalArgumentException
    }
}

運行結果:

c
d

六、迭代器的擴展

package Collections;

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

import org.apache.commons.collections4.IterableMap;
import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.Predicate;
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 liguodong
 */
@SuppressWarnings("all")
public class Demo06 {


    public static void main(String[] args) {
        mapIt();
        uniqueIt();
        filterIt();
        loopIt();
        arrayIt();
    }
    /**
     * map迭代器
     */
    public static void mapIt()
    {
        System.out.println("=======map迭代器=========");
        IterableMap map = new HashedMap<>();     
        map.put("a", "baby");
        map.put("b", "ohyeah");
        map.put("c", "doog");

        //使用MapIterator
        MapIterator it = map.mapIterator();
        while(it.hasNext())
        {
            //移動游標 it.next()
            String key = it.next();
            //或者使用如下方法
            /*it.next();
            String key = it.getKey();*/

            String value = it.getValue();
            System.out.println(key+"-->"+value);            
        }
    }

    /**
     * 去重迭代器
     */
    public static void uniqueIt()
    {
        System.out.println("=======去重迭代器=========");
        List list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("a");
        //去掉重復的過濾器
        Iterator it = new UniqueFilterIterator<>(list.iterator());
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }

    /**
     * 自定義迭代器
     */
    public static void filterIt()
    {
        System.out.println("======= 自定義迭代器=========");
        List list = new ArrayList<>();
        list.add("abcba");
        list.add("dad");
        list.add("dsfa");
        //自定義的條件
        Predicate pre = new Predicate() {
            @Override
            public boolean evaluate(String value) {
                //回文判斷
                return new StringBuilder(value).reverse().toString().equals(value);
            }
        };

        //去重重復的過濾器
        Iterator it = new FilterIterator(list.iterator(),pre);
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }

    /**
     * 循環迭代器
     */
    public static void loopIt()
    {
        System.out.println("======= 循環迭代器=========");
        List list = new ArrayList<>();
        list.add("refer");
        list.add("dad");
        list.add("sdafds"); 

        Iterator it = new LoopingIterator<>(list);      
        for(int i=0;i<5;i++)
        {
            System.out.println(it.next());
        }
    }


    /**
     * 數組迭代器
     */
    public static void arrayIt()
    {
        System.out.println("=======數組迭代器=========");
        int[] str = {1,2,3,4,5};

        //Iterator it = new ArrayListIterator<>(str);

        //也可以指定起始索引和結束索引
        Iterator it = new ArrayListIterator<>(str,1,3);
        while(it.hasNext())
        {
            System.out.println(it.next());
        }       
    }   
}

運行結果:

=======map迭代器=========
a-->baby
c-->doog
b-->ohyeah
=======去重迭代器=========
a
b
======= 自定義迭代器=========
abcba
dad
======= 循環迭代器=========
refer
dad
sdafds
refer
dad
=======數組迭代器=========
2
3

七、雙向Map

package Collections;

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、DualHashBidiMp:無序
 */
public class Demo07 {
    public static void main(String[] args) {
        hashMap();
        treeMap();
    }   
    /**
     * 無序的雙向Map
     */ 
    public static void hashMap()
    {
        System.out.println("=======無序的雙向Map=========");
        BidiMap map = new DualHashBidiMap<>();
        map.put("bj", "[email protected]");
        map.put("ddssf", "[email protected]");
        map.put("dsf", "[email protected]");
        //反轉
        System.out.println(map.inverseBidiMap().get("[email protected]"));

        //遍歷查看
        MapIterator it = map.inverseBidiMap().mapIterator();
        while(it.hasNext())
        {
            String key = it.next();
            String value = it.getValue();
            System.out.println(key+"-->"+value);
        }
    }

    /**
     * 有序的雙向Map
     */
    public static void treeMap()
    {
        System.out.println("=======有序的雙向Map=========");
        BidiMap map = new DualTreeBidiMap<>();
        map.put("bj", "[email protected]");
        map.put("ddssf", "[email protected]");
        map.put("dsf", "[email protected]");

        //遍歷查看
        MapIterator it = map.inverseBidiMap().mapIterator();
        while(it.hasNext())
        {
            String key = it.next();
            String value = it.getValue();
            System.out.println(key+"-->"+value);
        }
    }
}

運行結果:

=======無序的雙向Map=========
bj
[email protected]>ddssf
[email protected]>dsf
[email protected]>bj
=======有序的雙向Map=========
[email protected]>dsf
[email protected]>bj
[email protected]>ddssf

八、Bag包

package Collections;

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.HashMap 無序
 * 2.TreeMap 有序
 * 統計單詞的出現次數
 */
public class Demo08 {
    public static void main(String[] args) {
        hashBag();
        treeBag();
        wordcount();//統計單詞的出現次數 
    }

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

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

    public static void wordcount(){
        String str = "this is a cat and that is a micewhere is the food";
        String[]  strArray  = str.split(" ");
        Bag bag = new TreeBag<>();
        for(String temp:strArray)
        {
            bag.add(temp);
        }

        System.out.println("=====統計次數========");
        Set keys = bag.uniqueSet();
        for(String letter:keys)
        {
            System.out.println(letter+"-->"+bag.getCount(letter));
        }
    }   
}

運行結果:

=====無序的包========
b c a a a a 
=====有序的包========
a a a a b c 
=====統計次數========
a-->2
and-->1
cat-->1
food-->1
is-->3
micewhere-->1
that-->1
the-->1
this-->1

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved