Guava:谷歌開發的集合庫,經過build path->Add External JARs 把guava.jar包加進去。 版本控制工具:1.CVS 2.SVN 3.git 因此須要下載git客戶端。 import com.google.common.collect.ImmutableList; /** * 只讀設置 */ public class Demo01 { public static void main(String[] args) { List<String> list =new ArrayList<String>(); list.add("a"); list.add("b"); list.add("c"); //對原有的list進行包裝,相等於原有List的一個視圖,快照,不夠安全 List<String> readList =Collections.unmodifiableList(list); readList.add("d");//對這個視圖增操做,錯誤,拋出java.lang.UnsupportedOperationException(不被支持的異常)。 list.add("d"); //正確,改變原有List,視圖也一塊兒改變,沒有達到真正的目的,因此不夠安全。 // guava對只讀設置 安全可靠,而且相對簡單 List<String> immutableList =ImmutableList.of("a", "b", "c"); //初始化List immutableList.add("d");//java.lang.UnsupportedOperationException } } import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Sets; /** * 函數式編程 :解耦 * 一、Predicate * 二、Function * * 工具:Collections2.filter() 過濾器 * Collections2.transfer() 轉換 * Functions.compose()組合式函數編程 */ public class Demo02 { public static void main(String[] args) { //組合式函數編程 //確保容器中的字符串長度不超過5,超過進行截取,後所有大寫 List<String> list =Lists.newArrayList("bjsxt","good","happiness");//靜態建立List, //確保容器中的字符串長度不超過5,超過進行截取 Function<String,String> f1 =new Function<String,String>(){ @Override public String apply(String input) { return input.length()>5?input.substring(0,5):input; } }; //轉成大寫 Function<String,String> f2 =new Function<String,String>(){ @Override public String apply(String input) { return input.toUpperCase(); } }; //String =f2(f1(String)) Function<String,String> f =Functions.compose(f1, f2); Collection<String> resultCol =Collections2.transform(list, f); for(String temp:resultCol){ System.out.println(temp); } } /** * 轉換 */ public static void test2(){ //類型轉換 Set<Long> timeSet =Sets.newHashSet(); timeSet.add(10000000L); timeSet.add(99999999999999999L); timeSet.add(2000000000L); Collection<String> timeStrCol =Collections2.transform(timeSet, new Function<Long,String>(){ @Override public String apply(Long input) { return new SimpleDateFormat("yyyy-MM-dd").format(input); }}); for(String temp:timeStrCol){ System.out.println(temp); } } /** * 過濾器 */ public static void test1(){ //建立List 靜態初始化 List<String> list =Lists.newArrayList("moom","son","dad","bjsxt","refer"); //找出迴文 palindrome backwords mirror words //匿名內部類對象: 匿名內部類,同時建立類對象 Collection<String> palindromeList =Collections2.filter(list, new Predicate<String>(){ @Override public boolean apply(String input) {//若是這個類只使用一次,而且這個類的對象也只使用一次,就用匿名內部類對象。 //業務邏輯 return new StringBuilder(input).reverse().toString().equals(input);//字符串的反轉等於自身。 } }); for(String temp:palindromeList){ System.out.println(temp); } } } import com.google.common.base.Preconditions; import com.google.common.collect.Constraint; import com.google.common.collect.Constraints; import com.google.common.collect.Sets; /** * 加入約束條件:非空、長度驗證 * Constraint * Preconditions * Constraints */ public class Demo03 { public static void main(String[] args) { Set<String> sets =Sets.newHashSet(); //建立約束 Constraint<String> constraint =new Constraint<String>(){ @Override public String checkElement(String element) { //非空驗證 Preconditions.checkNotNull(element); //長度驗證 5-20爲字符串 Preconditions.checkArgument(element.length()>=5 && element.length()<=20); return element; } }; Set<String> cs =Constraints.constrainedSet(sets, constraint); //cs.add(null); //java.lang.NullPointerException //cs.add("good"); //java.lang.IllegalArgumentException cs.add("bjsxt"); for(String str:cs){ System.out.println(str); } } } import com.google.common.collect.Sets;//谷歌的jar包 import com.google.common.collect.Sets.SetView; /** * 集合的操做:交集、差集、並集 * Sets.intersection() * Sets.difference() * Sets.union(); */ public class Demo04 { public static void main(String[] args) { Set<Integer> sets =Sets.newHashSet(1,2,3,4,5,6); Set<Integer> sets2 =Sets.newHashSet(3,4,5,6,7,8,9); //交集 System.out.println("交集爲:"); SetView<Integer> intersection =Sets.intersection(sets, sets2); for(Integer temp:intersection){ System.out.println(temp);//3456 } //差集 System.out.println("差集爲:"); SetView<Integer> diff =Sets.difference(sets, sets2); for(Integer temp:diff){ System.out.println(temp);//12 } //並集 System.out.println("並集爲:"); SetView<Integer> union =Sets.union(sets, sets2); for(Integer temp:union){ System.out.println(temp);//123456789 } } } import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; /** * 統計單詞出現的次數 * 一、HashMap 分揀存儲+面向對象思惟 -->判斷 * 二、Multiset :無序+可重複 .count() 加強了可讀性 +操做簡單 * @author Administrator * */ public class Demo05 { public static void main(String[] args) { String str ="this is a cat and that is a mice where is the food"; //分割字符串 String[] strArray =str.split(" "); //存儲到Multiset中 Multiset<String> set =HashMultiset.create(); for(String strTemp:strArray){ set.add(strTemp); } //獲取全部的單詞 Set Set<String> letters =set.elementSet(); for(String temp:letters){ System.out.println(temp+"-->"+set.count(temp));//統計人員訪問網站的 次數 } /*mice-->1 that-->1 cat-->1 is-->3 food-->1 a-->2 the-->1 where-->1 this-->1 and-->1*/ } } import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; /** * 分析查看 教師 教授的每門課程 * Multimap :key-value key能夠重複 */ public class Demo06 { public static void main(String[] args) { Map<String,String> cours =new HashMap<String,String>(); //加入測試數據 cours.put("改革開放", "鄧爺爺"); cours.put("三個表明", "江主席"); cours.put("科學發展觀", "胡主席"); cours.put("和諧社會", "胡主席"); cours.put("八榮八恥", "胡主席"); cours.put(".1..", "習主席"); cours.put("..2.", "習主席"); cours.put(".3..", "習主席"); //Multimap Multimap<String,String> teachers =ArrayListMultimap.create(); //迭代器 Iterator<Map.Entry<String,String>> it =cours.entrySet().iterator(); while(it.hasNext()){ Map.Entry<String,String> entry =it.next(); String key =entry.getKey(); //課程 String value =entry.getValue(); //教師 //教師 -->課程 teachers.put(value, key); } //查看Multimap Set<String> keyset =teachers.keySet(); for(String key:keyset){ Collection<String> col =teachers.get(key); System.out.println(key+"-->"+col); } /*鄧爺爺-->[改革開放] 江主席-->[三個表明] 習主席-->[.3.., ..2., .1..] 胡主席-->[科學發展觀, 八榮八恥, 和諧社會]*/ } } import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; /** * HashMap 鍵惟一,值能夠重複 * BiMap:雙向Map(Bidirectional Map ) 鍵與值都不能重複(unique -valued map) */ public class Demo07 { public static void main(String[] args) { BiMap<String,String> bimap=HashBiMap.create(); bimap.put("bjsxt", "bjsxt@sina.com"); bimap.put("good","good@qq.com"); //經過郵箱找用戶 String user =bimap.inverse().get("good@qq.com"); System.out.println(user);//good System.out.println(bimap.inverse().inverse()==bimap);//true } } import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; import com.google.common.collect.Table.Cell; import com.google.common.collect.Tables; /** * 雙鍵的Map -->Table -->rowKey+columnKey+value//相似於一個表格,2個做爲key,另一個做爲value. * 一、方法 * 全部的行數據:cellSet() * 全部的學生: rowKeySet()//查看其中一列 * 全部的課程:columnKeySet()//查看另外一列 * 全部的成績: values()//查看全部的value * 學生對應的課程: rowMap() +get(學生) * row(學生) * 課程對應的學生: columnMap +get(課程) * column(課程) */ public class Demo08 { public static void main(String[] args) { Table<String,String,Integer> tables=HashBasedTable.create(); //測試數據 tables.put("a", "javase", 80); tables.put("b", "javase", 90); tables.put("a", "oracle", 100); tables.put("c", "oracle", 95); //全部的行數據 Set<Cell<String,String,Integer>> cells =tables.cellSet(); for(Cell<String,String,Integer> temp:cells){ System.out.println(temp.getRowKey()+"-->"+temp.getColumnKey()+"-->"+temp.getValue()); } System.out.println("==========學生查當作績=============="); System.out.print("學生\t"); //全部的課程 Set<String> cours =tables.columnKeySet(); for(String t:cours){ System.out.print(t+"\t"); } System.out.println(); //全部的學生 Set<String> stus =tables.rowKeySet(); for(String stu:stus){ System.out.print(stu+"\t"); Map<String,Integer> scores =tables.row(stu); for(String c:cours){ System.out.print(scores.get(c)+"\t"); } System.out.println(); } System.out.println("==========課程查當作績=============="); System.out.print("課程\t"); //全部的學生 Set<String> stuSet =tables.rowKeySet(); for(String t:stuSet){ System.out.print(t+"\t"); } System.out.println(); //全部的課程 Set<String> courSet =tables.columnKeySet(); for(String c:courSet){ System.out.print(c+"\t"); Map<String,Integer> scores =tables.column(c); for(String s:stuSet){ System.out.print(scores.get(s)+"\t"); } System.out.println(); } System.out.println("===========轉換==========="); Table<String,String,Integer> tables2 =Tables.transpose(tables); //全部的行數據 Set<Cell<String,String,Integer>> cells2 =tables2.cellSet(); for(Cell<String,String,Integer> temp:cells2){ System.out.println(temp.getRowKey()+"-->"+temp.getColumnKey()+"-->"+temp.getValue()); } } } 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替代 一、 new EqualPredicate<類型>(值) EqualPredicate.equalPredicate(值); 二、NotNullPredicate.INSTANCE 三、UniquePredicate.uniquePredicate() 四、自定義 new Predicate() +evaluate PredicateUtils.allPredicate(能夠傳2個以上的斷言器),andPredicate(只能傳2個斷言器),anyPredicate(多個斷言器,只要其中一個 爲true便可) PredicatedXxx.predicatedXxx(容器,判斷) * @author Administrator * */ public class Demo01 { @SuppressWarnings("unchecked") 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(null);//報異常 list.add("bj");//報異常 } /** * 判斷惟一 */ 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 notNull0 = 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不能添加null值。 list.add(1000L); list.add(null); //驗證失敗,出現異常 } /** * 比較相等判斷 */ public static void equal(){ System.out.println("======相等判斷======"); Predicate<String> pre0 =new EqualPredicate<String>("bjsxt");//實例化一個對象 Predicate<String> pre =EqualPredicate.equalPredicate("bjsxt");//建立對象 boolean flag =pre.evaluate("bj");//是否相等 System.out.println(flag); } } 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 類型轉化 一、new Transformer() +transform 二、SwitchTransformer CollectionUtils.collect(容器,轉換器) */ 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}; //轉換,將Employee轉成Level, 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()); /*(碼農:老馬,水平:養身中) (碼農:老裴,水平:賣身中)*/ } } /** * 內置類型的轉換 */ public static void inner(){ System.out.println("===內置類型轉換 長整形時間日期,轉成指定格式的字符串=="); //類型轉換器,將long類型轉成String, 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); } } } /** * 員工類 * @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+")"; } } /** * 等級類 * @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+")"; } } 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 閉包 封裝特定的業務功能 一、Closure 二、IfClosure IfClosure.ifClosure(斷言,功能1,功能2) 三、WhileClosure WhileClosure.whileClosure(斷言,功能,標識) 四、ChainedClosure.chainedClosure(功能列表); CollectionUtils.forAllDo(容器,功能類對象); */ public class Demo03 { 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視頻1",120,true)); goodsList.add(new Goods("javaee視頻2",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視頻1,價格:88.0,是否打折:是) (商品:javaee視頻2,價格: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);//empPre爲true則進入cols, //工具類 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視頻1",120,true)); goodsList.add(new Goods("javaee視頻2",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,subtract,discount); //關聯 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)*/ } } } 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?"是":"否")+")"; } } import org.apache.commons.collections4.CollectionUtils; /** * 集合操做 * 一、並集 * CollectionUtils.union(); * 二、交集 * CollectionUtils.intersection(); * CollectionUtils.retainAll(); * 三、差集 * CollectionUtils.subtract(); */ 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> 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); } } } 隊列: 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隊列(先進先出),棧(後進先出) 一、循環隊列:CircularFifoQueue 二、只讀隊列:不可改變隊列 UnmodifiableQueue 三、斷言隊列:PredicatedQueue.predicatedQueue() */ public class Demo05 { 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(null); } /** * 只讀隊列 */ 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"); que.add("b"); que.add("c"); //查看 for(int i=0;i<que.size();i++){ System.out.println(que.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; /** 迭代器的擴展 一、MapIterator 之後再也不使用map.keySet.iterator訪問 接口IterableMap,實現類 HashedMap 二、UniqueFilterIterator 去重迭代器 三、FilterIterator 自定義過濾 +Predicate 四、LoopingIterator 循環迭代器 五、ArrayListIterator 數組迭代器 */ public class Demo06 { 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> it0 =new ArrayListIterator<Integer>(arr); //指定起始索引和結束索引 Iterator<Integer> it =new ArrayListIterator<Integer>(arr,1,3); while(it.hasNext()){ System.out.println(it.next());//2,3 } } /** * 循環迭代器 */ 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<8;i++){ System.out.println(it.next()); /*refer dad bjsxt moom refer dad bjsxt moom*/ } } /** * 自定義迭代器 */ 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()); /*a b*/ } } /** * 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()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); /*a-->bjsxt c-->good b-->sxt*/ } } } 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() 實現類一、DualTreeBidiMap :有序 實現類二、DualHashBidiMap :無序 */ public class Demo07 { public static void main(String[] args) { hashMap(); treeMap(); } /** * 有序的雙向Map(key會自動排列) */ public static void treeMap(){ System.out.println("=====有序的雙向Map===="); BidiMap<String,String> map =new DualTreeBidiMap<String,String>(); map.put("zbj", "bj@test.com"); map.put("sxt", "sxt@qq.com");//{sxt=sxt@qq.com, zbj=bj@test.com} //遍歷查看 MapIterator<String,String> it =map.inverseBidiMap().mapIterator();//{bj@test.com=zbj, sxt@qq.com=sxt} while(it.hasNext()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); //bj@test.com-->zbj //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");//{sxt=sxt@qq.com, bj=bj@test.com} //反轉 System.out.println(map.inverseBidiMap().get("sxt@qq.com"));//先要反轉,而後經過value找到key,sxt //遍歷查看 MapIterator<String,String> it =map.inverseBidiMap().mapIterator();//{sxt@qq.com=sxt, bj@test.com=bj} while(it.hasNext()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); /*sxt@qq.com-->sxt bj@test.com-->bj*/ } } } import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.bag.TreeBag; /** 接口Bag 包 容許重複 實現類一、HashBag 無序 實現類二、TreeBag 有序 統計單詞的出現次數 */ 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);//[2:a,1:and,1:cat,1:food,3:is,1:mice,1:that,1:the,1:this,1:where] } System.out.println("====統計次數==="); Set<String> keys =bag.uniqueSet();//[a, and, cat, food, is, mice, that, the, this, where] for(String letter:keys){ System.out.println(letter+"-->"+bag.getCount(letter)); /*a-->2 and-->1 cat-->1 food-->1 is-->3 mice-->1 that-->1 the-->1 this-->1 where-->1*/ } } /** * 有序 */ 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");//[4:a,1:b,1:c],有序 Iterator<String> it =bag.iterator(); while(it.hasNext()){ System.out.println(it.next());//aaaabc } } /** * 無序 */ public static void hashBag(){ System.out.println("=====無序的包===="); Bag<String> bag =new HashBag<String>(); bag.add("a"); bag.add("a",5);//加5次a,[6:a] bag.remove("a", 2);//移除2個a,[4:a] bag.add("b"); bag.add("c");//[1:b,1:c,4:a],一個b,一個c,4個a, Iterator<String> it =bag.iterator(); while(it.hasNext()){ System.out.println(it.next());//bcaaaa } } } 總結: set沒有順序,順序指的是索引的順序不是指內容。 1.迭代器:Iterator, 2.比較器:實體類能夠排序(實現Comparable重寫compareTo),還能夠用排序比較器(實現Comparator重寫compare),TreeSet、TreeMap. 3.泛型:反泛型類,泛型方法,泛型接口,泛型擦出,通配符? 4.6個接口:Collection,set,List,Map,Iterator,Comparable 5.9個經常使用類: 1) 查看多餘修改時推薦使用ArrayList(add,remove,set(修改),get,foreach,)。 2) 修改多餘查看推薦使用LinkList,多了鏈頭與鏈尾的方法。 3)HashSet:元素不能重複,因此要求元素要重寫hashCode和equals方法. 4)Treeset:要求元素能夠排序或者提供排序的業務類。 5)HashMap:鍵不能重複必須重寫hashCode和equals方法,值能夠重複,put(),remove(),get(). 6)Properties:資源配置文件, 7)Hashtable:鍵與值都不能爲null, 8)Stack:棧 9)Collections:工具類