1. 程式人生 > >Apache Commons Collections基本操作(Predicate、Transformat、Closure等)

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<String> pre = new
EqualPredicate<String>("liguodong"); //Predicate<String> 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<Long> list = PredicatedList.predicatedList(new ArrayList<>(), notNull); list.add(1000L); //list.add(null);//null值為false, 驗證失敗,出現異常 } public static void Test003() { 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 Test004(){ 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<>(), 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<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<>();
        list.add(99999999L);
        list.add(30000L);

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

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

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

        Predicate<Employee> isLow = new Predicate<Employee>(){
            public boolean evaluate(Employee emp)
            {
                return emp.getSalary()<=10000;
            }
        };              
        Predicate<Employee> isHigh = new Predicate<Employee>() {
            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<>();
        list.add(new Employee("鳳姐",10000000));
        list.add(new Employee("犀利哥",1000));

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

        //遍歷容器
        Iterator<Level> 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<Employee> empList = new ArrayList<>();
        empList.add(new Employee("mark",20000));
        empList.add(new Employee("json",10000));
        empList.add(new Employee("Ivy",5000));

        //業務功能
        Closure<Employee> cols = new Closure<Employee>()
        {
            @Override
            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());
        }
    }


    /**
     * 二選一  如果打折商品,進行9折;否則滿百減20。
     */
    public static void ifClousure()
    {
        List<Goods> 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<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> pre = new Predicate<Goods>() {
            @Override
            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);
        }
    }



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

        //業務功能 每次上漲0.2
        Closure<Employee> cols = new Closure<Employee>()
        {
            @Override
            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());
        }
    }   



    /**
     *折上減   如果打折商品,先進行9折,如果還滿百,再減20
     */
    public static void chainClousure()
    {
        List<Goods> 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<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> 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<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);

        Set<Integer> set2 = new HashSet<>();
        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.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<String> que = new CircularFifoQueue<>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        que.add("d");
        //檢視
        for(int i=0;i<que.size();i++)
        {
            System.out.println(que.get(i));
        }
    }
    /**
     * 只讀佇列
     */
    public static void readOnly()
    {
        CircularFifoQueue<String> que = new CircularFifoQueue<>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        Queue<String> readOnlyOne = UnmodifiableQueue.unmodifiableQueue(que);
        //readOnlyOne.add("d");//java.lang.UnsupportedOperationException
    }

    /**
     * 斷言佇列
     */
    public static void predicate()
    {
        //迴圈佇列
        CircularFifoQueue<String> que = new CircularFifoQueue<>(2);
        que.add("a");
        que.add("b");
        que.add("c");
        Predicate notNull = NotNullPredicate.INSTANCE;
        //包裝成對應的佇列
        Queue<String> 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<String,String> map = new HashedMap<>();     
        map.put("a", "baby");
        map.put("b", "ohyeah");
        map.put("c", "doog");

        //使用MapIterator
        MapIterator<String,String> 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<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("a");
        //去掉重複的過濾器
        Iterator<String> it = new UniqueFilterIterator<>(list.iterator());
        while(it.hasNext())
        {
            System.out.println(it.next());
        }
    }

    /**
     * 自定義迭代器
     */
    public static void filterIt()
    {
        System.out.println("======= 自定義迭代器=========");
        List<String> list = new ArrayList<>();
        list.add("abcba");
        list.add("dad");
        list.add("dsfa");
        //自定義的條件
        Predicate<String> pre = new Predicate<String>() {
            @Override
            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 loopIt()
    {
        System.out.println("======= 迴圈迭代器=========");
        List<String> list = new ArrayList<>();
        list.add("refer");
        list.add("dad");
        list.add("sdafds"); 

        Iterator<String> 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<Integer> it = new ArrayListIterator<>(str);

        //也可以指定起始索引和結束索引
        Iterator<Integer> 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<String, String> 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<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 treeMap()
    {
        System.out.println("=======有序的雙向Map=========");
        BidiMap<String, String> map = new DualTreeBidiMap<>();
        map.put("bj", "[email protected]");
        map.put("ddssf", "[email protected]");
        map.put("dsf", "[email protected]");

        //遍歷檢視
        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
[email protected]126.com-->ddssf
bfdsfdsj@qq.com-->dsf
bj@test.com-->bj
=======有序的雙向Map=========
bfdsfdsj@qq.com-->dsf
bj@test.com-->bj
[email protected]126.com-->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<String> bag = new HashBag<>();
        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.print(it.next()+" ");
        }
        System.out.println();
    }

    //有序的包
    public static void treeBag()
    {
        System.out.println("=====有序的包========");
        Bag<String> bag = new TreeBag<>();
        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.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<String> bag = new TreeBag<>();
        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));
        }
    }   
}

執行結果:

=====無序的包========
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

相關推薦

Apache Commons Collections基本操作PredicateTransformatClosure

一、Predicate斷言 package Collections; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections4.Pre

UFT 基本操作描述性編程函數循環

ive dial 方法 wid 基本操作 logs pan log ron 1、描述性編程 class("描述性屬性1:=值","描述性屬性2:=值") 如輸入姓名,使用對象屬性方法: Dialog("Login").WinEdit("Agent Name:"

C# 用Linq的方式實現對Xml檔案的基本操作建立xml檔案增刪改查xml檔案節點資訊

1 private static void GetXmlNodeInforOld( string xmlPath) 2 { 3 try 4 { 5

二叉連結串列的儲存結構和基本操作各種遍歷求樹深度求樹葉個數

1.二叉樹的定義及性質 二叉樹是一種樹狀結構,它的特點是每個節點至多隻能有兩棵子樹,並且二叉樹的子樹有左右之分,其次序不能任意調換。 二叉樹具有以下重要性質: 性質 1 在二叉樹的第i層上至多有2^(i-1)個節點。 性質 2 深度為k的二叉樹至多有2^k-1個節點。 性

ID基本操作標尺,參考線,網格5.11

5.1 style 圖片 右鍵 目標 span pan shift 鼠標 參考線:標尺參考線,分欄參考線,出血參考線。在創建參考線之前確保標尺和參考線都可見。並且選中正確的跨頁和頁面作為目標, “版面”“創建參考線”可以輸入數值創建參考線。 跨頁參考線的創建:拖動參考線時鼠

ID基本操作在框架內處理文本5.28

alt 文本 符號 bubuko http 文檔 mage 選中 特殊符號 1.可以直接拖入文檔,word,excel,rtf,還可以選中文字,導出文本。 2.批量把一段文字改為另一段。還可以改特殊符號。定義範圍。 ID基本操作(在框架內處理文本)5.28

C#中對資料庫的基本操作增刪改以及呼叫儲存過程

因為最近在寫web API的時候需要對資料庫操作,所以要用到ADO.NET,因為之前沒有接觸過.NET所以也是一邊上網查資料看C#書一邊寫,現在對這塊基礎的部分已經掌握了,現在寫下來只是想對自己前段時間的學習做個簡單的總結,也便於自己以後查閱(網上有很多類似的資源,大家可以

c++實現鏈棧的基本操作附帶main函式 可編譯執行

資料結構老師佈置了鏈棧的基本操作,讓我們儘量嘗試用class實現,然後我在網上參考了一部分,自己寫了一個,有不足之處懇請大家指出 /*  *  檔名:鏈棧.c  *    鏈棧的實現  *    版本:2.0  *    時間:2016.11.4  *    作者:Wan

對PPT的操作文字替換,圖片插入

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Text;using System.Threading.Tasks;using POWER

3PPSPRPDF編輯器Acrobat中的基基本操作

確認密碼 安全性 inf 選中 編輯器 png nbsp 打開 順序 本文介紹一些關於圖片、視頻、PDF的最常用操作: 圖像方面:旋轉、裁剪、拼接、水印(文字)、導出     軟件:Photoshop 視頻方面:剪切(拼接)、水印(文字、字幕)、導出    軟件:Premi

Hadoop HDFS基本操作ubuntu16.04 Hadoop 3.0.3

hdfs shell的基本操作以及hdfsWeb檢視檔案 在安裝好hadoop叢集併成功的啟動了hdfs之後,我們就可以利用hdfs對檔案進行操作了,一下是對檔案的一些基本操作 特別注意:訪問HDFS目錄時,一定要帶有/  否則命令會出錯! hdfs基本操作 1、查詢命令

02 ndarray的屬性 ndarray的基本操作索引切片變形連線切分副本聚合操作矩陣操作排序Panda資料結構Series建立索引與切片屬性與方法運算

二、ndarray的屬性 4個必記引數: ndim:維度 shape:形狀(各維度的長度) size:總長度 dtype:元素型別 import matplotlib.pyplot as plt ndarr = plt.imread("./jin.png") plt.

python對字典的基本操作遍歷排序總結

Python字典容器 python中的字典同其他語言中的字典作用一樣,都是用來儲存資料的容器。只不過不同於其他序列型資料用下標來訪問其中的物件,而是以關鍵字key來訪問其中的物件value。另外,字典也被稱為關聯陣列或者雜湊表。 字典的應用場景有很多,下面通過一個投票的例

Java MongoDB基本操作查詢刪除更新

正在持續更新... MongoDB中的資料 { "_id": ObjectId("57c43caed4c63d7e39b5dc48"), "name": "張三", "age": 15, "arr": [1,2,3], "arrOb

Docker基本操作容器管理建立映象

什麼是Docker 映象? Docker 映象就是一個只讀的模板。 例如:一個映象可以包含一個完整的 ubuntu 作業系統環境,裡面僅安裝了 Apache 或使用者需要的其它應用程式。映象可以用來建立 Docker 容器。 Docker 提供了一個很簡單的機制來建立映象或者

連結串列的基本操作插入,刪除,排序逆置

連結串列是資料結構中最基本的,也是非常經典的,在面試筆試中也是經常出現的題,但是萬變不離其宗,只要掌握了基本的操作,一起盡在掌控。 特別要注意的一點是處理時千萬要把是否為頭進行判斷,做為一個特例,或者建立連結串列就先固定建立一個表頭,這樣程式碼就沒這麼多判斷了。 #i

Collections集合操作ListSetMap-巧用工具類

先從一個簡單例子看一下這些東西可以帶給我們怎樣的便利,下面的程式碼會完成字串去重+排序功能。 String str = "asdasdasdx"; ArrayList<String> list = new ArrayList(Arrays.asList(str.

MongoDB的基本操作插入刪除更新索引)

###一、MongoDB與Sql資料庫概念上的區別   MongoDB與SQL資料庫有幾個概念上的問題是不一樣的,主要有sql資料庫中的表(table)在MongoDB中叫集合(collection);sql資料庫表中一行記錄(row)在MongoDB中叫文件(

佇列的基本操作順序佇列迴圈佇列鏈式佇列

        佇列也是一種線性表,是一種先進先出的線性結構。佇列只允許在表的一端進行插入(入隊)、刪除(出隊)操作。允許插入的一端稱為隊尾,允許刪除的一端稱為隊頭。        佇列的基本操作包括: 初始化佇列:InitQueue(Q)

單鏈表的基本操作讀取插入刪除及優缺點總結

1.單鏈表的讀取 獲取連結串列第i個數據的演算法思路: 1. 宣告一個指標p指向連結串列的第一個結點,初始化j從1開始; 2. 當j< i 時,遍歷連結串列,讓p的指標向後移動,不斷指向下一結點,j累加1; 3. 若到連結串列末尾p為空,說明第i個