1. package com.bjsxt.others.commons;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.apache.commons.collections4.Predicate;
  7. import org.apache.commons.collections4.PredicateUtils;
  8. import org.apache.commons.collections4.functors.EqualPredicate;
  9. import org.apache.commons.collections4.functors.NotNullPredicate;
  10. import org.apache.commons.collections4.functors.UniquePredicate;
  11. import org.apache.commons.collections4.list.PredicatedList;
  12. import org.junit.Test;
  13.  
  14. /**
  15. 函数式编程 之 Predicate 断言
  16. 封装条件或判别式 if..else替代
  17. 1、 new EqualPredicate<类型>(值)
  18. EqualPredicate.equalPredicate(值);
  19. 2、NotNullPredicate.INSTANCE
  20. 3、UniquePredicate.uniquePredicate()
  21. 4、自定义
  22. new Predicate() +evaluate
  23. PredicateUtils.allPredicate andPredicate anyPredicate
  24. PredicatedXxx.predicatedXxx(容器,判断)
  25. * @author Administrator
  26. *
  27. */
  28. public class Demo01 {
  29.  
  30. /**
  31. * @param args
  32. */
  33. public static void main(String[] args) {
  34. System.out.println("======自定义判断======");
  35. //自定义的判别式
  36. Predicate<String> selfPre =new Predicate<String>(){
  37. @Override
  38. public boolean evaluate(String object) {
  39. return object.length()>=5 && object.length()<=20;
  40.  
  41. }};
  42. Predicate notNull=NotNullPredicate.notNullPredicate();
  43.  
  44. Predicate all =PredicateUtils.allPredicate(notNull,selfPre);
  45.  
  46. List<String> list =PredicatedList.predicatedList(new ArrayList<String>(),all);
  47. list.add("bjsxt");
  48. list.add(null);
  49. list.add("bj");
  50.  
  51. }
  52. /**
  53. * 判断唯一
  54. */
  55. public static void unique(){
  56. System.out.println("====唯一性判断====");
  57. Predicate<Long> uniquePre =UniquePredicate.uniquePredicate();
  58. List<Long> list =PredicatedList.predicatedList(new ArrayList<Long>(), uniquePre);
  59. list.add(100L);
  60. list.add(200L);
  61. list.add(100L); //出现重复值,抛出异常
  62. }
  63.  
  64. /**
  65. * 判断非空
  66. */
  67. public static void notNull(){
  68. System.out.println("====非空判断====");
  69. //Predicate notNull=NotNullPredicate.INSTANCE;
  70. Predicate notNull=NotNullPredicate.notNullPredicate();
  71. //String str ="bjs";
  72. String str =null;
  73. System.out.println(notNull.evaluate(str)); //如果非空为true ,否则为false
  74.  
  75. //添加容器值的判断
  76. List<Long> list =PredicatedList.predicatedList(new ArrayList<Long>(), notNull);
  77. list.add(1000L);
  78. list.add(null); //验证失败,出现异常
  79. }
  80.  
  81. /**
  82. * 比较相等判断
  83. */
  84. @Test
  85. public static void equal(){
  86. System.out.println("======相等判断======");
  87. //Predicate<String> pre =new EqualPredicate<String>("bjsxt");
  88. Predicate<String> pre =EqualPredicate.equalPredicate("bjsxt");
  89. boolean flag =pre.evaluate("bj");
  90. System.out.println(flag);
  91. }
  92.  
  93. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Collection;
  6. import java.util.Iterator;
  7. import java.util.List;
  8.  
  9. import org.apache.commons.collections4.CollectionUtils;
  10. import org.apache.commons.collections4.Predicate;
  11. import org.apache.commons.collections4.Transformer;
  12. import org.apache.commons.collections4.functors.SwitchTransformer;
  13. import org.junit.Test;
  14.  
  15. /**
  16. 解耦,业务处理与判断进行分类
  17. 函数式编程 Transformer 类型转化
  18. 1、new Transformer() +transform
  19. 2、SwitchTransformer
  20. CollectionUtils.collect(容器,转换器)
  21. * @author Administrator
  22. *
  23. */
  24. public class Demo02 {
  25.  
  26. /**
  27. * @param args
  28. */
  29. public static void main(String[] args) {
  30. System.out.println("===自定义类型转换==");
  31. //判别式
  32. Predicate<Employee> isLow=new Predicate<Employee>(){
  33.  
  34. @Override
  35. public boolean evaluate(Employee emp) {
  36. return emp.getSalary()<10000;
  37. }
  38.  
  39. };
  40. Predicate<Employee> isHigh=new Predicate<Employee>(){
  41.  
  42. @Override
  43. public boolean evaluate(Employee emp) {
  44. return emp.getSalary()>=10000;
  45. }
  46.  
  47. };
  48. Predicate[] pres ={isLow,isHigh};
  49.  
  50. //转换
  51. Transformer<Employee,Level> lowTrans =new Transformer<Employee,Level>(){
  52.  
  53. @Override
  54. public Level transform(Employee input) {
  55. return new Level(input.getName(),"卖身中");
  56. }};
  57.  
  58. Transformer<Employee,Level> highTrans =new Transformer<Employee,Level>(){
  59.  
  60. @Override
  61. public Level transform(Employee input) {
  62. return new Level(input.getName(),"养身中");
  63. }};
  64. Transformer[] trans ={lowTrans,highTrans};
  65.  
  66. //二者进行了关联
  67. Transformer switchTrans =new SwitchTransformer(pres, trans, null);
  68.  
  69. //容器
  70. List<Employee> list =new ArrayList<Employee>();
  71. list.add(new Employee("老马",1000000));
  72. list.add(new Employee("老裴",999));
  73.  
  74. Collection<Level> levelList = CollectionUtils.collect(list,switchTrans);
  75.  
  76. //遍历容器
  77. Iterator<Level> levelIt =levelList.iterator();
  78. while(levelIt.hasNext()){
  79. System.out.println(levelIt.next());
  80. }
  81.  
  82. }
  83. /**
  84. * 内置类型的转换
  85. */
  86. @Test
  87. public static void inner(){
  88. System.out.println("===内置类型转换 长整形时间日期,转成指定格式的字符串==");
  89. //类型转换器
  90. Transformer<Long,String> trans =new Transformer<Long,String>(){
  91.  
  92. @Override
  93. public String transform(Long input) {
  94. return new SimpleDateFormat("yyyy年MM月dd日").format(input);
  95. }};
  96. //容器
  97. List<Long> list =new ArrayList<Long>();
  98. list.add(999999999999L);
  99. list.add(300000000L);
  100.  
  101. //工具类 程序猿出钱---开发商---农民工出力
  102. Collection<String> result=CollectionUtils.collect(list, trans);
  103. //遍历查看结果
  104. for(String time:result){
  105. System.out.println(time);
  106. }
  107. }
  108.  
  109. }
  1. package com.bjsxt.others.commons;
  2. /**
  3. * 员工类
  4. * @author Administrator
  5. *
  6. */
  7. public class Employee {
  8. private String name;
  9. private double salary;
  10. //alt +/
  11. public Employee() {
  12. }
  13. //alt+shift+s o
  14. public Employee(String name, double salary) {
  15. super();
  16. this.name = name;
  17. this.salary = salary;
  18. }
  19. //alt+shift+s +r tab 回车 shift+tab 回车
  20. public String getName() {
  21. return name;
  22. }
  23. public void setName(String name) {
  24. this.name = name;
  25. }
  26. public double getSalary() {
  27. return salary;
  28. }
  29. public void setSalary(double salary) {
  30. this.salary = salary;
  31. }
  32. @Override
  33. public String toString() {
  34. return "(码农:"+this.name+",敲砖钱:"+this.salary+")";
  35. }
  36.  
  37. }
  1. package com.bjsxt.others.commons;
  2. /**
  3. * 等级类
  4. * @author Administrator
  5. *
  6. */
  7. public class Level {
  8. private String name;
  9. private String level;
  10. public Level() {
  11. // TODO Auto-generated constructor stub
  12. }
  13. public Level(String name, String level) {
  14. super();
  15. this.name = name;
  16. this.level = level;
  17. }
  18. public String getName() {
  19. return name;
  20. }
  21. public void setName(String name) {
  22. this.name = name;
  23. }
  24. public String getLevel() {
  25. return level;
  26. }
  27. public void setLevel(String level) {
  28. this.level = level;
  29. }
  30. @Override
  31. public String toString() {
  32. return "(码农:"+this.name+",水平:"+this.level+")";
  33. }
  34. }
  1. package com.bjsxt.others.commons;
  2.  
  3. public class Goods {
  4. private String name;
  5. private double price;
  6. //折扣
  7. private boolean discount;
  8. public Goods() {
  9. // TODO Auto-generated constructor stub
  10. }
  11. public Goods(String name, double price, boolean discount) {
  12. super();
  13. this.name = name;
  14. this.price = price;
  15. this.discount = discount;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public double getPrice() {
  24. return price;
  25. }
  26. public void setPrice(double price) {
  27. this.price = price;
  28. }
  29. public boolean isDiscount() {
  30. return discount;
  31. }
  32. public void setDiscount(boolean discount) {
  33. this.discount = discount;
  34. }
  35.  
  36. @Override
  37. public String toString() {
  38. return "(商品:"+this.name+",价格:"+this.price+",是否打折:"+(discount?"是":"否")+")";
  39. }
  40.  
  41. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6.  
  7. import org.apache.commons.collections4.Closure;
  8. import org.apache.commons.collections4.CollectionUtils;
  9. import org.apache.commons.collections4.Predicate;
  10. import org.apache.commons.collections4.functors.ChainedClosure;
  11. import org.apache.commons.collections4.functors.IfClosure;
  12. import org.apache.commons.collections4.functors.WhileClosure;
  13.  
  14. /**
  15. 函数式编程 Closure 闭包 封装特定的业务功能
  16. 1、Closure
  17. 2、IfClosure IfClosure.ifClosure(断言,功能1,功能2)
  18. 3、WhileClosure WhileClosure.whileClosure(断言,功能,标识)
  19. 4、ChainedClosure.chainedClosure(功能列表);
  20. CollectionUtils.forAllDo(容器,功能类对象);
  21. * @author Administrator
  22. *
  23. */
  24. public class Demo03 {
  25.  
  26. /**
  27. * @param args
  28. */
  29. public static void main(String[] args) {
  30. //basic();
  31. ifClosure();
  32. //whileClosure();
  33. chainClosure();
  34. }
  35. /**
  36. * 折上减 先打折商品,进行9折,满百再减20
  37. */
  38. public static void chainClosure(){
  39. List<Goods> goodsList =new ArrayList<Goods>();
  40. goodsList.add(new Goods("javase视频",120,true));
  41. goodsList.add(new Goods("javaee视频",100,false));
  42. goodsList.add(new Goods("高新技术视频",80,false));
  43.  
  44. //满百减20
  45. Closure<Goods> subtract=new Closure<Goods>(){
  46. public void execute(Goods goods) {
  47. if(goods.getPrice()>=100){
  48. goods.setPrice(goods.getPrice()-20);
  49. }
  50. }};
  51. //打折
  52. Closure<Goods> discount=new Closure<Goods>(){
  53. public void execute(Goods goods) {
  54. if(goods.isDiscount()){
  55. goods.setPrice(goods.getPrice()*0.9);
  56. }
  57. }};
  58.  
  59. //链式操作
  60. Closure<Goods> chainClo=ChainedClosure.chainedClosure(discount,subtract);
  61.  
  62. //关联
  63. CollectionUtils.forAllDo(goodsList,chainClo);
  64.  
  65. //查看操作后的数据
  66. for(Goods temp:goodsList){
  67. System.out.println(temp);
  68. }
  69.  
  70. }
  71.  
  72. /**
  73. * 确保所有的员工工资都大于10000,如果已经超过的不再上涨
  74. */
  75. public static void whileClosure(){
  76. //数据
  77. List<Employee> empList =new ArrayList<Employee>();
  78. empList.add(new Employee("bjsxt",20000));
  79. empList.add(new Employee("is",10000));
  80. empList.add(new Employee("good",5000));
  81.  
  82. //业务功能 每次上涨0.2
  83. Closure<Employee> cols=new Closure<Employee>(){
  84. public void execute(Employee emp) {
  85. emp.setSalary(emp.getSalary()*1.2);
  86. }};
  87.  
  88. //判断
  89. Predicate<Employee> empPre=new Predicate<Employee>(){
  90. @Override
  91. public boolean evaluate(Employee emp) {
  92. return emp.getSalary()<10000;
  93. }
  94. };
  95. //false 表示 while结构 先判断后执行 true do..while 先执行后判断
  96. Closure<Employee> whileCols =WhileClosure.whileClosure(empPre, cols, false);
  97.  
  98. //工具类
  99. CollectionUtils.forAllDo(empList, whileCols) ;
  100.  
  101. //操作后的数据
  102. Iterator<Employee> empIt=empList.iterator();
  103. while(empIt.hasNext()){
  104. System.out.println(empIt.next());
  105. }
  106. }
  107. /**
  108. * 二选一 如果是打折商品,进行9折,否则满百减20
  109. */
  110. public static void ifClosure(){
  111. List<Goods> goodsList =new ArrayList<Goods>();
  112. goodsList.add(new Goods("javase视频",120,true));
  113. goodsList.add(new Goods("javaee视频",100,false));
  114. goodsList.add(new Goods("高新技术视频",80,false));
  115.  
  116. //满百减20
  117. Closure<Goods> subtract=new Closure<Goods>(){
  118. public void execute(Goods goods) {
  119. if(goods.getPrice()>=100){
  120. goods.setPrice(goods.getPrice()-20);
  121. }
  122. }};
  123. //打折
  124. Closure<Goods> discount=new Closure<Goods>(){
  125. public void execute(Goods goods) {
  126. if(goods.isDiscount()){
  127. goods.setPrice(goods.getPrice()*0.9);
  128. }
  129. }};
  130.  
  131. //判断
  132. Predicate<Goods> pre=new Predicate<Goods>(){
  133. public boolean evaluate(Goods goods) {
  134. return goods.isDiscount();
  135. }};
  136.  
  137. //二选一
  138. Closure<Goods> ifClo=IfClosure.ifClosure(pre, discount,subtract);
  139.  
  140. //关联
  141. CollectionUtils.forAllDo(goodsList,ifClo);
  142.  
  143. //查看操作后的数据
  144. for(Goods temp:goodsList){
  145. System.out.println(temp);
  146. }
  147.  
  148. }
  149. /**
  150. * 基本操作
  151. */
  152. public static void basic(){
  153. //数据
  154. List<Employee> empList =new ArrayList<Employee>();
  155. empList.add(new Employee("bjsxt",20000));
  156. empList.add(new Employee("is",10000));
  157. empList.add(new Employee("good",5000));
  158.  
  159. //业务功能
  160. Closure<Employee> cols=new Closure<Employee>(){
  161. public void execute(Employee emp) {
  162. emp.setSalary(emp.getSalary()*1.2);
  163. }};
  164.  
  165. //工具类
  166. CollectionUtils.forAllDo(empList, cols) ;
  167.  
  168. //操作后的数据
  169. Iterator<Employee> empIt=empList.iterator();
  170. while(empIt.hasNext()){
  171. System.out.println(empIt.next());
  172. }
  173. }
  174.  
  175. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Set;
  6.  
  7. import org.apache.commons.collections4.CollectionUtils;
  8.  
  9. /**
  10. * 集合操作
  11. * 1、并集
  12. * CollectionUtils.union();
  13. * 2、交集
  14. * CollectionUtils.intersection();
  15. * CollectionUtils.retainAll();
  16. * 3、差集
  17. * CollectionUtils.subtract();
  18. * @author Administrator
  19. *
  20. */
  21. public class Demo04 {
  22.  
  23. /**
  24. * @param args
  25. */
  26. public static void main(String[] args) {
  27. Set<Integer> set1 =new HashSet<Integer>();
  28. set1.add(1);
  29. set1.add(2);
  30. set1.add(3);
  31.  
  32. Set<Integer> set2 =new HashSet<Integer>();
  33. set2.add(2);
  34. set2.add(3);
  35. set2.add(4);
  36.  
  37. //并集
  38. System.out.println("=========并集============");
  39. Collection<Integer> col =CollectionUtils.union(set1,set2);
  40. for(Integer temp:col){
  41. System.out.println(temp);
  42. }
  43. //交集
  44. System.out.println("=========交集============");
  45. //col =CollectionUtils.intersection(set1, set2);
  46. col =CollectionUtils.retainAll(set1, set2);
  47. for(Integer temp:col){
  48. System.out.println(temp);
  49. }
  50. //差集
  51. System.out.println("=========差集============");
  52. col =CollectionUtils.subtract(set1, set2);
  53. for(Integer temp:col){
  54. System.out.println(temp);
  55. }
  56. }
  57.  
  58. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import java.util.Queue;
  4.  
  5. import org.apache.commons.collections4.Predicate;
  6. import org.apache.commons.collections4.functors.NotNullPredicate;
  7. import org.apache.commons.collections4.queue.CircularFifoQueue;
  8. import org.apache.commons.collections4.queue.PredicatedQueue;
  9. import org.apache.commons.collections4.queue.UnmodifiableQueue;
  10.  
  11. /**
  12. Queue队列
  13. 1、循环队列:CircularFifoQueue
  14. 2、只读队列:不可改变队列 UnmodifiableQueue
  15. 3、断言队列:PredicatedQueue.predicatedQueue()
  16. * @author Administrator
  17. *
  18. */
  19. public class Demo05 {
  20.  
  21. /**
  22. * @param args
  23. */
  24. public static void main(String[] args) {
  25. //circular();
  26. //readOnly();
  27. predicate();
  28. }
  29. /**
  30. * 断言队列
  31. */
  32. public static void predicate(){
  33. //循环队列
  34. CircularFifoQueue<String> que =new CircularFifoQueue<String>(2);
  35. que.add("a");
  36. que.add("b");
  37. que.add("c");
  38. Predicate notNull=NotNullPredicate.INSTANCE;
  39. //包装成对应的队列
  40. Queue<String> que2=PredicatedQueue.predicatedQueue(que, notNull);
  41. que2.add(null);
  42. }
  43. /**
  44. * 只读队列
  45. */
  46. public static void readOnly(){
  47. //循环队列
  48. CircularFifoQueue<String> que =new CircularFifoQueue<String>(2);
  49. que.add("a");
  50. que.add("b");
  51. que.add("c");
  52. Queue<String> readOnlyQue =UnmodifiableQueue.unmodifiableQueue(que);
  53. readOnlyQue.add("d");
  54. }
  55. /**
  56. * 循环队列
  57. */
  58. public static void circular(){
  59. //循环队列
  60. CircularFifoQueue<String> que =new CircularFifoQueue<String>(2);
  61. que.add("a");
  62. que.add("b");
  63. que.add("c");
  64. //查看
  65. for(int i=0;i<que.size();i++){
  66. System.out.println(que.get(i));
  67. }
  68.  
  69. }
  70.  
  71. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Iterator;
  5. import java.util.List;
  6.  
  7. import org.apache.commons.collections4.BidiMap;
  8. import org.apache.commons.collections4.IterableMap;
  9. import org.apache.commons.collections4.MapIterator;
  10. import org.apache.commons.collections4.Predicate;
  11. import org.apache.commons.collections4.bidimap.DualHashBidiMap;
  12. import org.apache.commons.collections4.iterators.ArrayListIterator;
  13. import org.apache.commons.collections4.iterators.FilterIterator;
  14. import org.apache.commons.collections4.iterators.LoopingIterator;
  15. import org.apache.commons.collections4.iterators.UniqueFilterIterator;
  16. import org.apache.commons.collections4.map.HashedMap;
  17.  
  18. /**
  19. 迭代器的扩展
  20. 1、MapIterator 以后不再使用map.keySet.iterator访问
  21. IterableMap HashedMap
  22. 2、UniqueFilterIterator 去重迭代器
  23. 3、FilterIterator 自定义过滤 +Predicate
  24. 4、LoopingIterator 循环迭代器
  25. 5、ArrayListIterator 数组迭代器
  26. * @author Administrator
  27. *
  28. */
  29. public class Demo06 {
  30.  
  31. /**
  32. * @param args
  33. */
  34. public static void main(String[] args) {
  35. //mapIt();
  36. //uniqueIt();
  37. //filterIt();
  38. //loopIt();
  39. arrayIt();
  40. }
  41. /**
  42. * 数组迭代器
  43. */
  44. public static void arrayIt(){
  45. System.out.println("===== 数组迭代器 ====");
  46. int[] arr ={1,2,3,4,5};
  47. //数组迭代器
  48. //Iterator<Integer> it =new ArrayListIterator<Integer>(arr);
  49. //指定起始索引和结束索引
  50. Iterator<Integer> it =new ArrayListIterator<Integer>(arr,1,3);
  51. while(it.hasNext()){
  52. System.out.println(it.next());
  53. }
  54. }
  55. /**
  56. * 循环迭代器
  57. */
  58. public static void loopIt(){
  59. System.out.println("===== 循环迭代器 ====");
  60. List<String> list =new ArrayList<String>();
  61. list.add("refer");
  62. list.add("dad");
  63. list.add("bjsxt");
  64. list.add("moom");
  65.  
  66. Iterator<String> it =new LoopingIterator(list);
  67. for(int i=0;i<15;i++){
  68. System.out.println(it.next());
  69. }
  70. }
  71. /**
  72. * 自定义迭代器
  73. */
  74. public static void filterIt(){
  75. System.out.println("=====自定义迭代器 ====");
  76. List<String> list =new ArrayList<String>();
  77. list.add("refer");
  78. list.add("dad");
  79. list.add("bjsxt");
  80. list.add("moom");
  81. //自定义条件判断
  82. Predicate<String> pre =new Predicate<String>(){
  83. public boolean evaluate(String value) {
  84. //回文判断
  85. return new StringBuilder(value).reverse().toString().equals(value);
  86. }};
  87.  
  88. //去除重复的过滤器
  89. Iterator<String> it =new FilterIterator(list.iterator(),pre);
  90. while(it.hasNext()){
  91. System.out.println(it.next());
  92. }
  93. }
  94. /**
  95. * 去重迭代器
  96. */
  97. public static void uniqueIt(){
  98. System.out.println("=====去重迭代器 ====");
  99. List<String> list =new ArrayList<String>();
  100. list.add("a");
  101. list.add("b");
  102. list.add("a");
  103. //去除重复的过滤器
  104. Iterator<String> it =new UniqueFilterIterator(list.iterator());
  105. while(it.hasNext()){
  106. System.out.println(it.next());
  107. }
  108. }
  109. /**
  110. * map迭代器
  111. */
  112. public static void mapIt(){
  113. System.out.println("=====map迭代器====");
  114. IterableMap<String,String> map =new HashedMap<String,String>();
  115. map.put("a","bjsxt");
  116. map.put("b", "sxt");
  117. map.put("c", "good");
  118. //使用 MapIterator
  119. MapIterator<String,String> it =map.mapIterator();
  120. while(it.hasNext()){
  121. //一定要it.next()
  122. /*
  123. it.next();
  124. String key =it.getKey();
  125. */
  126. String key =it.next();
  127. String value =it.getValue();
  128. System.out.println(key+"-->"+value);
  129. }
  130.  
  131. }
  132.  
  133. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import org.apache.commons.collections4.BidiMap;
  4. import org.apache.commons.collections4.MapIterator;
  5. import org.apache.commons.collections4.bidimap.DualHashBidiMap;
  6. import org.apache.commons.collections4.bidimap.DualTreeBidiMap;
  7.  
  8. /**
  9. 双向Map 要求键与值都不能重复
  10. BidiMap inverseBidiMap()
  11. 1、DualTreeBidiMap :有序
  12. 2、DualHashBidiMap :无序
  13. * @author Administrator
  14. *
  15. */
  16. public class Demo07 {
  17.  
  18. /**
  19. * @param args
  20. */
  21. public static void main(String[] args) {
  22. //hashMap();
  23. treeMap();
  24. }
  25. /**
  26. * 有序的双向Map
  27. */
  28. public static void treeMap(){
  29. System.out.println("=====有序的双向Map====");
  30. BidiMap<String,String> map =new DualTreeBidiMap<String,String>();
  31. map.put("bj", "bj@test.com");
  32. map.put("sxt", "sxt@qq.com");
  33. //遍历查看
  34. MapIterator<String,String> it =map.inverseBidiMap().mapIterator();
  35. while(it.hasNext()){
  36. String key =it.next();
  37. String value =it.getValue();
  38. System.out.println(key+"-->"+value);
  39. }
  40. }
  41.  
  42. /**
  43. * 无序的双向Map
  44. */
  45. public static void hashMap(){
  46. System.out.println("=====无序的双向Map====");
  47. BidiMap<String,String> map =new DualHashBidiMap<String,String>();
  48. map.put("bj", "bj@test.com");
  49. map.put("sxt", "sxt@qq.com");
  50. //反转
  51. System.out.println(map.inverseBidiMap().get("sxt@qq.com"));
  52. //遍历查看
  53. MapIterator<String,String> it =map.inverseBidiMap().mapIterator();
  54. while(it.hasNext()){
  55. String key =it.next();
  56. String value =it.getValue();
  57. System.out.println(key+"-->"+value);
  58. }
  59. }
  60.  
  61. }
  1. package com.bjsxt.others.commons;
  2.  
  3. import java.util.Iterator;
  4. import java.util.Set;
  5.  
  6. import org.apache.commons.collections4.Bag;
  7. import org.apache.commons.collections4.bag.HashBag;
  8. import org.apache.commons.collections4.bag.TreeBag;
  9.  
  10. /**
  11. Bag 包 允许重复
  12. 1、HashBag 无序
  13. 2、TreeBag 有序
  14. 统计单词的出现次数
  15. * @author Administrator
  16. *
  17. */
  18. public class Demo08 {
  19.  
  20. /**
  21. * @param args
  22. */
  23. public static void main(String[] args) {
  24. //hashBag();
  25. //treeBag();
  26. String str ="this is a cat and that is a mice where is the food";
  27. //分割字符串
  28. String[] strArray =str.split(" ");
  29. Bag<String> bag =new TreeBag<String>();
  30. for(String temp:strArray){
  31. bag.add(temp);
  32. }
  33.  
  34. System.out.println("====统计次数===");
  35. Set<String> keys =bag.uniqueSet();
  36. for(String letter:keys){
  37. System.out.println(letter+"-->"+bag.getCount(letter));
  38. }
  39.  
  40. }
  41. /**
  42. * 有序
  43. */
  44. public static void treeBag(){
  45. System.out.println("=====有序的包====");
  46. Bag<String> bag =new TreeBag<String>();
  47. bag.add("a");
  48. bag.add("a",5);
  49. bag.remove("a", 2);
  50. bag.add("b");
  51. bag.add("c");
  52. Iterator<String> it =bag.iterator();
  53. while(it.hasNext()){
  54. System.out.println(it.next());
  55. }
  56. }
  57.  
  58. /**
  59. * 无序
  60. */
  61. public static void hashBag(){
  62. System.out.println("=====无序的包====");
  63. Bag<String> bag =new HashBag<String>();
  64. bag.add("a");
  65. bag.add("a",5);
  66. bag.remove("a", 2);
  67. bag.add("b");
  68. bag.add("c");
  69. Iterator<String> it =bag.iterator();
  70. while(it.hasNext()){
  71. System.out.println(it.next());
  72. }
  73. }
  74.  
  75. }
  1. package collection;
  2.  
  3. import java.util.NoSuchElementException;
  4.  
  5. /**
  6. * @author SUNHAN
  7. * @Date: 2014年9月29日
  8. */
  9. public class SLinkedList {
  10. private transient int size=0;
  11. private transient Node head=new Node(null,null,null);//用头结点来表示整个链表
  12.  
  13. public SLinkedList(){//默认构造方法
  14. head.next=head;
  15. head.previous=head;
  16. }
  17.  
  18. public void add(Object element){//在末尾插入元素
  19. Node Nnode=new Node(element,head,head.previous);
  20. Nnode.previous.next=Nnode;
  21. Nnode.next.previous=Nnode;
  22. size++;
  23. }
  24.  
  25. public void addBefore(Object o,Node e){
  26. Node newNode=new Node(o,e,e.previous);
  27. newNode.previous.next=newNode;
  28. newNode.next.previous=newNode;
  29. size++;
  30.  
  31. }
  32.  
  33. public void add(int index,Object o){//俩参数的add()方法
  34. addBefore(o,(index==size?head:node(index)));
  35. }
  36.  
  37. private Node node(int index){
  38. if(index<0||index>=size){
  39. throw new IndexOutOfBoundsException("Index: "+index+", Size: "+size);
  40. }
  41. Node e=head;//从header开始循环
  42. if(index<size/2){
  43. for(int i=0;i<=index;i++){//对用户而言,头结点是不可见的
  44. e=e.next;
  45. }
  46. }
  47. else{
  48. for(int i=size;i>index;i--){
  49. e=e.previous;
  50. }
  51. }
  52. return e;
  53. }
  54.  
  55. public Object remove(int index){
  56. Node e=node(index);
  57. remove(e);
  58. return e.element;
  59. }
  60.  
  61. private void remove(Node e){
  62. if(e==head){
  63. throw new NoSuchElementException();
  64. }
  65. e.previous.next=e.next;
  66. e.next.previous=e.previous;
  67. size--;
  68. }
  69. }
  70. class Node {
  71. Object element;
  72. Node next;
  73. Node previous;
  74.  
  75. public Node(Object element,Node next,Node previous){//带仨参的构造函数
  76. this.element=element;
  77. this.next=next;
  78. this.previous=previous;
  79. }
  80. }
  1. package collection;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Set;
  8.  
  9. /**
  10. * @author SUNHAN
  11. * @Date: 2014年9月29日
  12. *
  13. */
  14. public class SIterator {
  15. public static void main(String[] args) {
  16. Set set=new HashSet();
  17.  
  18. set.add("aa");
  19. set.add("bb");
  20. set.add("cc");
  21. Iterator iter=set.iterator();
  22. while(iter.hasNext()){
  23. String str=(String) iter.next();
  24. System.err.println(str);
  25. }
  26.  
  27. for(Iterator iter1=set.iterator();iter.hasNext();){
  28. String str=(String) iter1.next();
  29. System.err.println(str);
  30. }
  31.  
  32. List list=new ArrayList();
  33. list.add("xxx");
  34. list.add("yyy");
  35. list.add("zzz");
  36. for(Object o:list){
  37. System.err.println(o.toString());
  38. }
  39. }
  40. }
  1. package collection;
  2.  
  3. import java.util.HashSet;
  4. import java.util.LinkedList;
  5. import java.util.ListIterator;
  6. import java.util.Set;
  7. /**
  8. * @author SUNHAN
  9. * @Date: 2014年9月29日
  10. * @param <K>
  11. * @param <V>
  12. */
  13. @SuppressWarnings("unchecked")
  14. public class SimpleHashMap<K, V> {
  15.  
  16. private static final int ARRAY_SiZE = 997;
  17. private LinkedList<MapEntry<K, V>>[] buckets = new LinkedList[ARRAY_SiZE];
  18. public V put(K key, V value) { //添加一个键值对
  19. V oldValue = null;
  20. int index = Math.abs(key.hashCode()) % ARRAY_SiZE; //通过哈希码取绝对值再取模操作得到key的索引值
  21. if(buckets[index] == null) {
  22. buckets[index] = new LinkedList<MapEntry<K, V>>();
  23. }
  24. LinkedList bucket = buckets[index];
  25. MapEntry newEntry = new MapEntry<K, V>(key, value);
  26. ListIterator<MapEntry<K, V>> itr = bucket.listIterator();
  27. while(itr.hasNext()) { //遍历,是否key已存在
  28. MapEntry<K, V> entry = itr.next();
  29. if(entry.getKey().equals(key)) { //存在
  30. oldValue = entry.getValue();
  31. itr.set(newEntry); //将新值覆盖旧值
  32. return oldValue;
  33. }
  34. }
  35. bucket.add(newEntry);//添加新键值对
  36. return oldValue;
  37. }
  38.  
  39. public V get(Object key) { //通过key得到value
  40. int index = Math.abs(key.hashCode()) % ARRAY_SiZE; //通过哈希码取绝对值再取模操作得到key的索引值
  41. if(buckets[index] == null) {
  42. return null;
  43. }
  44. for(MapEntry<K ,V> entry : buckets[index]) {
  45. if(entry.getKey().equals(key)) {
  46. return entry.getValue();
  47. }
  48. }
  49. return null;
  50. }
  51.  
  52. public Set<MapEntry<K, V>> entrySet() { //返回一个set
  53. Set<MapEntry<K, V>> set = new HashSet<MapEntry<K, V>>();
  54. for(LinkedList<MapEntry<K, V>> bucket : buckets) { //遍历数组以及LinkedList,将所有存在的键值对放进set中返回
  55. if(bucket == null) continue;
  56. for(MapEntry<K, V> entry : bucket) {
  57. set.add(entry);
  58. }
  59. }
  60. return set;
  61. }
  62.  
  63. public V remove(Object key) { //移除指定的键值对,并返回value
  64. V oldValue = null;
  65. int index = Math.abs(key.hashCode()) % ARRAY_SiZE;
  66. if(buckets[index] == null) {
  67. return null;
  68. }
  69. for(MapEntry<K, V> entry : buckets[index]) {
  70. if(entry.getKey().equals(key)) {
  71. oldValue = entry.getValue();
  72. buckets[index].remove(entry);
  73. return oldValue;
  74. }
  75. }
  76. return oldValue;
  77. }
  78.  
  79. public void clear() { //清除整个map
  80. for(int i = 0; i < buckets.length; i++) {
  81. if(buckets[i] != null) {
  82. buckets[i] = null;
  83. }
  84. }
  85. }
  86.  
  87. static class MapEntry<K, V>{
  88. K key;
  89. V value;
  90. public MapEntry(K key, V value) {
  91. this.key = key;
  92. this.value = value;
  93. }
  94.  
  95. public K getKey() {
  96. return key;
  97. }
  98.  
  99. public V getValue() {
  100. return value;
  101. }
  102.  
  103. public V setValue(V value) {
  104. V old = this.value;
  105. this.value = value;
  106. return old;
  107. }
  108.  
  109. @Override
  110. public int hashCode() {
  111. return key == null ? 0 : key.hashCode()
  112. ^ (value == null ? 0 : value.hashCode());
  113. }
  114.  
  115. @Override
  116. public boolean equals(Object o) {
  117. if (!(o instanceof MapEntry)) {
  118. return false;
  119. }
  120. MapEntry<K, V> me = (MapEntry<K, V>) o;
  121. return (key == null ? me.getKey() == null : key.equals(me.getKey()))
  122. && (value == null ? me.getValue() == null : value.equals(me
  123. .getValue()));
  124. }
  125.  
  126. @Override
  127. public String toString() {
  128. return key + "=" + value;
  129. }
  130. }
  131. }
  1. package collection;
  2.  
  3. import java.util.HashMap;
  4.  
  5. public class SHashSet {
  6.  
  7. HashMap map;
  8. private static final Object PRERSENT=new Object();
  9.  
  10. int size;
  11.  
  12. public int size(){
  13. return map.size();
  14. }
  15. public SHashSet(){
  16. map=new HashMap();
  17. }
  18.  
  19. public void add(Object o){
  20. map.put(0, PRERSENT);
  21. }
  22.  
  23. public static void main(String[] args) {
  24.  
  25. }
  26. }

Commons-Collections 集合工具类的使用的更多相关文章

  1. Collections集合工具类,集合嵌套,集合综合案例斗地主

    1 Collections集合工具类 (可以对比Arrays工具类共同记忆) 常用方法: 例: import java.util.ArrayList; import java.util.Collect ...

  2. java第十九天,Collections集合工具类的使用

    Collections Java中集合都实现了Collection接口,那么针对集合一些特定的功能,有没有一个接口或类能够统一的集成一些集合必要的功能呢?当然能.它就是--Collections集合工 ...

  3. Collections集合工具类常用的方法

    java.utils.Collections //是集合工具类,用来对集合进行操作.部分方法如下: public static <T> boolean addAll(Collection& ...

  4. Collections集合工具类的常用方法

    Collections集合工具类的方法 addAll与shuffle import java.util.ArrayList; import java.util.Collections; /* - ja ...

  5. 可变参数和Collections集合工具类

    可变参数 /** * 可变参数:jdk1.5后出现的新特性 * 使用前期: * 当方法的参数列表数据类型已经确定的时候但是参数的个数不确定的时候就可以使用可变参数 * 使用格式:定义方法的时候使用 * ...

  6. Collections 集合工具类

    集合工具类  包括很多静态方法来操作集合list 而Collections则是集合类的一个工具类/帮助类,其中提供了一系列静态方法,用于对集合中元素进行排序.搜索以及线程安全等各种操作. 1) 排序( ...

  7. Collections集合工具类的方法_sort(List)和sort(List,Comparator)方法

    Comparator比较器 我们还是先研究这个方法 public static <T> void sort(List<T> list):将集合中元素按照默认规则排序. 不过这次 ...

  8. 可变参数和Collections集合工具类的方法_addAll&shuffle

    可变参数 可变参数:是JDK1.5之后出现的新特性 使用前提:当方法的参数列表数据类型已经确定,但是参数的个数不确定,就可以使用可变参数 使用格式:定义方法时使用 ~修饰符 返回值类型 方法名(数据类 ...

  9. [Guava学习笔记]Collections: 集合工具类

    我的技术博客经常被流氓网站恶意爬取转载.请移步原文:http://www.cnblogs.com/hamhog/p/3861431.html,享受整齐的排版.有效的链接.正确的代码缩进.更好的阅读体验 ...

  10. Collections集合工具类

    一.Collection与Collections Collection 是所有单列集合的根接口 Collection 是操作集合的工具类 二.Collections中常见的方法:(大都是static方 ...

随机推荐

  1. html5基础知识点

    1.WEB基础知识 1.WEB 与 Internet 1.Internet 互联网 若干台计算机 通过 网线 所连接而成的物理设备 主要服务: 1.Telnet 2.Email 3.WWW(Word ...

  2. C# 模拟按下回车键自动登录

    private void Form1_Load(object sender, EventArgs e) { //this.Show(); this.Activate(); //this.Focus() ...

  3. 获取贴图及IES文件

    最近看了一下以前写的关于收集贴图的函数...又完善了一下,老链接:http://www.cnblogs.com/3dxy/p/3988751.html fn saveusedmaps spath se ...

  4. MongoDB学习笔记六:进阶指南

    [数据库命令]『命令的工作原理』MongoDB中的命令其实是作为一种特殊类型的查询来实现的,这些查询针对$cmd集合来执行.runCommand仅仅是接受命令文档,执行等价查询,因此,> db. ...

  5. jquery'中的匿名函数

        //jquery'中的匿名函数 (function(){ alert("this is a test"); })(); //和这个基于jQuery的比较下: $(funct ...

  6. clientX、pageX、scrollLeft、offsetLeft、clientWidth、screen.width的用法和区别

    一.定义和用法 1.event.clientX:事件对象的水平偏移量: event.clientY:事件对象的垂直偏移量: 2.event.pageX:事件对象加上滚动距离后的水平偏移量: event ...

  7. pm2使用

    简单教程 首先需要安装pm2: npm install -g pm2 运行: pm2 start app.js 初次安装并运行,会有一个高大上的界面: 高大上的界面 直接我们介绍过forever,那么 ...

  8. Git 常见问题: unable to negotiate with *.*.*.*: no matching key exchange methodfound...

    在Windows上更新了git 版本后,clone/pull时出现错误, unable to negotiate with *.*.*.*: no matching key exchange meth ...

  9. Verilog HDL那些事_建模篇笔记(实验七:数码管电路驱动)

    1.同步动态扫描 多个数码管的显示采用的是同步动态扫描方法,同步动态扫描指的是:行信号和列信号同步扫描,是一种并行操作. 2.数码管驱动电路实现思路      如果要求数码管显示我们想要的数字,首先需 ...

  10. IOS-细节错误

    当页面显示时一直奔溃,错误提示-[UICachedDeviceWhiteColor pointSize]: unrecognized selector sent to instance 原因是设置导航 ...