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) { Listlist =new ArrayList (); list.add("a"); list.add("b"); list.add("c"); //对原有的list进行包装,相等于原有List的一个视图,快照,不够安全 List readList =Collections.unmodifiableList(list); readList.add("d");//对这个视图增操作,错误,抛出java.lang.UnsupportedOperationException(不被支持的异常)。 list.add("d"); //正确,改变原有List,视图也一起改变,没有达到真正的目的,所以不够安全。 // guava对只读设置 安全可靠,并且相对简单 List 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; /** * 函数式编程 :解耦 * 1、Predicate * 2、Function * * 工具:Collections2.filter() 过滤器 * Collections2.transfer() 转换 * Functions.compose()组合式函数编程 */ public class Demo02 { public static void main(String[] args) { //组合式函数编程 //确保容器中的字符串长度不超过5,超过进行截取,后全部大写 List list =Lists.newArrayList("bjsxt","good","happiness");//静态创建List, //确保容器中的字符串长度不超过5,超过进行截取 Function f1 =new Function (){ @Override public String apply(String input) { return input.length()>5?input.substring(0,5):input; } }; //转成大写 Function f2 =new Function (){ @Override public String apply(String input) { return input.toUpperCase(); } }; //String =f2(f1(String)) Function f =Functions.compose(f1, f2); Collection resultCol =Collections2.transform(list, f); for(String temp:resultCol){ System.out.println(temp); } } /** * 转换 */ public static void test2(){ //类型转换 Set timeSet =Sets.newHashSet(); timeSet.add(10000000L); timeSet.add(99999999999999999L); timeSet.add(2000000000L); Collection timeStrCol =Collections2.transform(timeSet, new Function (){ @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 list =Lists.newArrayList("moom","son","dad","bjsxt","refer"); //找出回文 palindrome backwords mirror words //匿名内部类对象: 匿名内部类,同时创建类对象 Collection palindromeList =Collections2.filter(list, new Predicate (){ @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 sets =Sets.newHashSet(); //创建约束 Constraint constraint =new Constraint (){ @Override public String checkElement(String element) { //非空验证 Preconditions.checkNotNull(element); //长度验证 5-20为字符串 Preconditions.checkArgument(element.length()>=5 && element.length()<=20); return element; } }; Set 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 sets =Sets.newHashSet(1,2,3,4,5,6); Set sets2 =Sets.newHashSet(3,4,5,6,7,8,9); //交集 System.out.println("交集为:"); SetView intersection =Sets.intersection(sets, sets2); for(Integer temp:intersection){ System.out.println(temp);//3456 } //差集 System.out.println("差集为:"); SetView diff =Sets.difference(sets, sets2); for(Integer temp:diff){ System.out.println(temp);//12 } //并集 System.out.println("并集为:"); SetView 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; /** * 统计单词出现的次数 * 1、HashMap 分拣存储+面向对象思维 -->判断 * 2、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 set =HashMultiset.create(); for(String strTemp:strArray){ set.add(strTemp); } //获取所有的单词 Set Set 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 cours =new HashMap (); //加入测试数据 cours.put("改革开放", "邓爷爷"); cours.put("三个代表", "江主席"); cours.put("科学发展观", "胡主席"); cours.put("和谐社会", "胡主席"); cours.put("八荣八耻", "胡主席"); cours.put(".1..", "习主席"); cours.put("..2.", "习主席"); cours.put(".3..", "习主席"); //Multimap Multimap teachers =ArrayListMultimap.create(); //迭代器 Iterator > it =cours.entrySet().iterator(); while(it.hasNext()){ Map.Entry entry =it.next(); String key =entry.getKey(); //课程 String value =entry.getValue(); //教师 //教师 -->课程 teachers.put(value, key); } //查看Multimap Set keyset =teachers.keySet(); for(String key:keyset){ Collection 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 bimap=HashBiMap.create(); bimap.put("bjsxt", "[email protected]"); bimap.put("good","[email protected]"); //通过邮箱找用户 String user =bimap.inverse().get("[email protected]"); 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. * 1、方法 * 所有的行数据:cellSet() * 所有的学生: rowKeySet()//查看其中一列 * 所有的课程:columnKeySet()//查看另一列 * 所有的成绩: values()//查看所有的value * 学生对应的课程: rowMap() +get(学生) * row(学生) * 课程对应的学生: columnMap +get(课程) * column(课程) */ public class Demo08 { public static void main(String[] args) { Table tables=HashBasedTable.create(); //测试数据 tables.put("a", "javase", 80); tables.put("b", "javase", 90); tables.put("a", "oracle", 100); tables.put("c", "oracle", 95); //所有的行数据 Set > cells =tables.cellSet(); for(Cell | temp:cells){ System.out.println(temp.getRowKey()+"-->"+temp.getColumnKey()+"-->"+temp.getValue()); } System.out.println("==========学生查看成绩=============="); System.out.print("学生\t"); //所有的课程 Set cours =tables.columnKeySet(); for(String t:cours){ System.out.print(t+"\t"); } System.out.println(); //所有的学生 Set stus =tables.rowKeySet(); for(String stu:stus){ System.out.print(stu+"\t"); Map 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 stuSet =tables.rowKeySet(); for(String t:stuSet){ System.out.print(t+"\t"); } System.out.println(); //所有的课程 Set courSet =tables.columnKeySet(); for(String c:courSet){ System.out.print(c+"\t"); Map scores =tables.column(c); for(String s:stuSet){ System.out.print(scores.get(s)+"\t"); } System.out.println(); } System.out.println("===========转换==========="); Table tables2 =Tables.transpose(tables); //所有的行数据 Set > cells2 =tables2.cellSet(); for(Cell | 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替代 1、 new EqualPredicate<类型>(值) EqualPredicate.equalPredicate(值); 2、NotNullPredicate.INSTANCE 3、UniquePredicate.uniquePredicate() 4、自定义 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 selfPre =new Predicate (){ @Override public boolean evaluate(String object) { return object.length()>=5 && object.length()<=20; }}; Predicate notNull=NotNullPredicate.notNullPredicate(); Predicate all =PredicateUtils.allPredicate(notNull,selfPre);//多个断言器 List list =PredicatedList.predicatedList(new ArrayList (),all);//用这个断言器来限制容器。 list.add("bjsxt"); list.add(null);//报异常 list.add("bj");//报异常 } /** * 判断唯一 */ public static void unique(){ 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 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 list =PredicatedList.predicatedList(new ArrayList (), notNull);//要求容器list不能添加null值。 list.add(1000L); list.add(null); //验证失败,出现异常 } /** * 比较相等判断 */ public static void equal(){ System.out.println("======相等判断======"); Predicate pre0 =new EqualPredicate ("bjsxt");//实例化一个对象 Predicate 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 类型转化 1、new Transformer() +transform 2、SwitchTransformer CollectionUtils.collect(容器,转换器) */ public class Demo02 { public static void main(String[] args) { System.out.println("===自定义类型转换=="); //判别式 Predicate isLow=new Predicate (){//匿名内部类 @Override public boolean evaluate(Employee emp) { return emp.getSalary()<10000; } }; Predicate isHigh=new Predicate (){//匿名内部类 @Override public boolean evaluate(Employee emp) { return emp.getSalary()>=10000; } }; Predicate[] pres ={isLow,isHigh}; //转换,将Employee转成Level, 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("老马",1000000)); list.add(new Employee("老裴",999)); Collection levelList = CollectionUtils.collect(list,switchTrans);//参数为容器和转换规则 //遍历容器 Iterator levelIt =levelList.iterator(); while(levelIt.hasNext()){ System.out.println(levelIt.next()); /*(码农:老马,水平:养身中) (码农:老裴,水平:卖身中)*/ } } /** * 内置类型的转换 */ public static void inner(){ System.out.println("===内置类型转换 长×××时间日期,转成指定格式的字符串=="); //类型转换器,将long类型转成String, Transformer trans =new Transformer (){ @Override public String transform(Long input) { return new SimpleDateFormat("yyyy年MM月dd日").format(input); }}; //容器 List list =new ArrayList (); list.add(999999999999L); list.add(300000000L); //工具类 ,程序猿出钱---开发商---农民工出力 Collection 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 闭包 封装特定的业务功能 1、Closure 2、IfClosure IfClosure.ifClosure(断言,功能1,功能2) 3、WhileClosure WhileClosure.whileClosure(断言,功能,标识) 4、ChainedClosure.chainedClosure(功能列表); CollectionUtils.forAllDo(容器,功能类对象); */ public class Demo03 { public static void main(String[] args) { basic(); ifClosure(); whileClosure(); chainClosure(); } /** * 折上减 先打折商品,进行9折,满百再减20 */ public static void chainClosure(){ List goodsList =new ArrayList (); goodsList.add(new Goods("javase视频1",120,true)); goodsList.add(new Goods("javaee视频2",100,false)); goodsList.add(new Goods("高新技术视频",80,false)); //满百减20 Closure subtract=new Closure (){ public void execute(Goods goods) { if(goods.getPrice()>=100){ goods.setPrice(goods.getPrice()-20); } }}; //打折 Closure discount=new Closure (){ public void execute(Goods goods) { if(goods.isDiscount()){ goods.setPrice(goods.getPrice()*0.9); } }}; //链式操作 Closure 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 empList =new ArrayList (); empList.add(new Employee("bjsxt",20000)); empList.add(new Employee("is",10000)); empList.add(new Employee("good",5000)); //业务功能 每次上涨0.2 Closure cols=new Closure (){ 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);//empPre为true则进入cols, //工具类 CollectionUtils.forAllDo(empList, whileCols) ; //操作后的数据 Iterator 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 goodsList =new ArrayList (); goodsList.add(new Goods("javase视频1",120,true)); goodsList.add(new Goods("javaee视频2",100,false)); goodsList.add(new Goods("高新技术视频",80,false)); //满百减20 Closure subtract=new Closure (){ public void execute(Goods goods) { if(goods.getPrice()>=100){ goods.setPrice(goods.getPrice()-20); } }}; //打折 Closure discount=new Closure (){ public void execute(Goods goods) { if(goods.isDiscount()){ goods.setPrice(goods.getPrice()*0.9); } }}; //判断 Predicate pre=new Predicate (){ public boolean evaluate(Goods goods) { return goods.isDiscount(); }}; //二选一 Closure 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 empList =new ArrayList (); empList.add(new Employee("bjsxt",20000)); empList.add(new Employee("is",10000)); empList.add(new Employee("good",5000)); //业务功能 Closure cols=new Closure (){//匿名内部类对象 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()); /*(码农: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; /** * 集合操作 * 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.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队列(先进先出),栈(后进先出) 1、循环队列:CircularFifoQueue 2、只读队列:不可改变队列 UnmodifiableQueue 3、断言队列:PredicatedQueue.predicatedQueue() */ public class Demo05 { public static void main(String[] args) { circular(); readOnly(); predicate(); } /** * 断言队列 */ 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); } /** * 只读队列 */ public static void readOnly(){ //循环队列 CircularFifoQueue que =new CircularFifoQueue (2); que.add("a"); que.add("b"); que.add("c"); Queue readOnlyQue =UnmodifiableQueue.unmodifiableQueue(que); readOnlyQue.add("d"); } /** * 循环队列 */ public static void circular(){ //循环队列 CircularFifoQueue que =new CircularFifoQueue (2); que.add("a"); que.add("b"); que.add("c"); //查看 for(int i=0;i it0 =new ArrayListIterator (arr); //指定起始索引和结束索引 Iterator it =new ArrayListIterator (arr,1,3); while(it.hasNext()){ System.out.println(it.next());//2,3 } } /** * 循环迭代器 */ public static void loopIt(){ System.out.println("===== 循环迭代器 ===="); List list =new ArrayList (); list.add("refer"); list.add("dad"); list.add("bjsxt"); list.add("moom"); Iterator 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 list =new ArrayList (); list.add("refer"); list.add("dad"); list.add("bjsxt"); list.add("moom"); //自定义条件判断 Predicate pre =new Predicate (){ 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()); /*refer dad moom*/ } } /** * 去重迭代器 */ 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()); /*a b*/ } } /** * map迭代器 */ public static void mapIt(){ System.out.println("=====map迭代器===="); IterableMap map =new HashedMap (); map.put("a","bjsxt"); map.put("b", "sxt"); map.put("c", "good"); //使用 MapIterator MapIterator 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() 实现类1、DualTreeBidiMap :有序 实现类2、DualHashBidiMap :无序 */ public class Demo07 { public static void main(String[] args) { hashMap(); treeMap(); } /** * 有序的双向Map(key会自动排列) */ public static void treeMap(){ System.out.println("=====有序的双向Map===="); BidiMap map =new DualTreeBidiMap (); map.put("zbj", "[email protected]"); map.put("sxt", "[email protected]");//{[email protected], [email protected]} //遍历查看 MapIterator it =map.inverseBidiMap().mapIterator();//{[email protected]=zbj, [email protected]=sxt} while(it.hasNext()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); //[email protected]>zbj //[email protected]>sxt } } /** * 无序的双向Map */ public static void hashMap(){ System.out.println("=====无序的双向Map===="); BidiMap map =new DualHashBidiMap (); map.put("bj", "[email protected]"); map.put("sxt", "[email protected]");//{[email protected], [email protected]} //反转 System.out.println(map.inverseBidiMap().get("[email protected]"));//先要反转,然后通过value找到key,sxt //遍历查看 MapIterator it =map.inverseBidiMap().mapIterator();//{[email protected]=sxt, [email protected]=bj} while(it.hasNext()){ String key =it.next(); String value =it.getValue(); System.out.println(key+"-->"+value); /*[email protected]>sxt [email protected]>bj*/ } } } import org.apache.commons.collections4.Bag; import org.apache.commons.collections4.bag.HashBag; import org.apache.commons.collections4.bag.TreeBag; /** 接口Bag 包 允许重复 实现类1、HashBag 无序 实现类2、TreeBag 有序 统计单词的出现次数 */ public class Demo08 { /** * @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 bag =new TreeBag (); 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 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 bag =new TreeBag (); bag.add("a"); bag.add("a",5); bag.remove("a", 2); bag.add("b"); bag.add("c");//[4:a,1:b,1:c],有序 Iterator it =bag.iterator(); while(it.hasNext()){ System.out.println(it.next());//aaaabc } } /** * 无序 */ public static void hashBag(){ System.out.println("=====无序的包===="); Bag bag =new HashBag (); 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 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:工具类
原文链接:https://www.cnblogs.com/yaowen/p/4833576.html