现在的位置: 首页 > 综合 > 正文

Java Collection Framework扩展Apache Common Collections介绍

2019年09月28日 ⁄ 综合 ⁄ 共 44259字 ⁄ 字号 评论关闭

Google Guava库 http://ifeve.com/google-guava/

Apache commons: http://commons.apache.org/

JDK8特性

为Java标准的Collections API提供了相当好的补充。在此基础上对其常用的数据结构操作进行了很好的封装、抽象和补充。保证性能的同时大大简化代码。

包的分类:

      

       

四)此包的分类:
    根据集合类型,大致将此包的类归纳为9类:
    Bag -- 在org.apache.commons.collections包中定义的接口,它extends java.util.Collection,而它的实现类都被放在下面的bag包中。HashBag是Bag接口的一个标准实现。而BagUtils提供一组static的方法让调用者获取经过不同装饰后的Bag实例.具体用法见代码样例

   Buffer (4.0改变为Queue队列)-- 定义在org.apache.commons.collections包下面的接口,用于表示按一定顺序除去成员对象的collection如队列等。具体的实现类在org.apache.commons.collections.buffer 包下可以找到。最简单直接的Buffer实现类是UnboundedFifoBuffer,提供先进先出的大小可变的队列。而BoundedFifoBuffer则是对其大小进行了限制,是固定大小的先进先出队列。BlockingBuffer要在多线程的环境中才能体现出它的价值,尤其是当我们需要实现某种流水线时这个BlockingBuffer很有用:每个流水线上的组件从上游的BlockingBuffer获取数据,处理后放到下一个BlockingBuffer中依次传递。BlockingBuffer的核心特色通俗点说就是如果你向它要东西,而它暂时还没有的话,你可以一直等待直至拿到为止。PriorityBuffer则提供比一般的先进先出Buffer更强的控制力:我们可以自定义Comparator给它,告诉它怎么判定它的成员的先后顺序,优先级最高的最先走。此外还有执行类型检查的TypedBuffer、或者不可改变的UnmodifiableBuffer等等

    Map -- 在java.util.Map的基础上扩展的接口和类。BidiMap,直译就是双向Map,可以通过key找到value,也可以通过value找到key,这在我们日常的代码-名称匹配的时候很方便:因为我们除了需要通过代码找到名称之外,往往也需要处理用户输入的名称,然后获取其代码。需要注意的是BidiMap当中不光key不能重复,value也不可以。MultiMap,就是说一个key不在是简单的指向一个对象,而是一组对象,add()和remove()的时候跟普通的Map无异,只是在get()时返回一个Collection,利用MultiMap,我们就可以很方便的往一个key上放数量不定的对象,也就实现了一对多。LazyMap,意思就是这个Map中的键/值对一开始并不存在,当被调用到时才创建。

    Collection -- 用也各collection之间的类型转换。典型的是TypedCollection,它实际上的作用就是提供一个decorate方法,我们传进去一个Collection和需要的类型甄别信息java.lang.Class,它给我们创建一个全新的强类型的Collection。(暂无样例代码,以后补充)

    Comparator -- 提供了一些Comparator的实现类(都在org.apache.commons.collections.comparators包下面)BooleanComparator – 用于排序一组Boolean对象,指明先true还是先false;ComparableComparator – 用于排序实现了java.lang.Comparable接口的对象(我们常用的Java类如String、Integer、Date、Double、File、Character等等都实现了Comparable接口);ComparatorChain
– 定义一组Comparator链,链中的Comparator对象会被依次执行;FixedOrderComparator – 用于定义一个特殊的顺序,对一组对象按照这样的自定义顺序进行排序;NullComparator – 让null值也可参与比较,可以设定为先null或者后null;
ReverseComparator – 将原有的Comparator效果反转;TransformingComparator – 将一个Comparator装饰为具有Transformer效果的Comparator。

    Predicate --它以一个Object对象为参数,处理后返回一个boolean值,检验某个对象是否满足某个条件。CommonsCollections也提供了一组定义好的Predicate类供我们使用,这些类都放在org.apache.commons.collections.functors包中。当然,我们也可以自定义Predicate,只要实现这个Predicate接口即可。

    Transformer --我们有时候需要将某个对象转换成另一个对象供另一组方法调用,而这两类对象的类型有可能并不是出于同一个继承体系的,或者说出了很基本的Object之外没有共同的父类,或者我们根本不关心他们是不是有其他继承关系,甚至就是同一个类的实例只是对我们而言无所谓,我们为了它能够被后续的调用者有意义的识别和处理,在这样的情形,我们就可以利用Transformer。除了基本的转型Transformer之外,CommonsCollections还提供了Transformer链和带条件的Transformer,使得我们很方便的组装出有意义的转型逻辑。

    Closure -- 这一组接口和类提供一个操作对象的execute方法,为我们在处理一系列对象时可以将处理逻辑分离出来。ChainedClosure可以包装一组Closure作为整体执行;IfClosure在创建时需要提供给它一个Predicate和两个Closure,执行时先做Predicate判定再决定执行哪一个Closure;SwitchClosure跟SwitchTransformer类似,根据创建时传入的Predicate组和Closure组对应执行;WhileClosure则根据创建时传入的Predicate做判断,如果为true则执行Closure,直到Predicate返回false;等等。

    Iterator --java.util.Iterator接口定义了标准的Collection遍历方法,但是如果不做改变的使用它,我们得到的是从头到尾一次性的遍历。假如我们需要循环遍历,假如我们需要遍历某一段,假如我们需要遍历满足某些条件的元素,等等等等,我们就不能完全依赖于这个Iterator的标准实现了。除非我们宁可在此基础上在调用的代码中多加一些判断,不过这样的话代码就会显得混乱,时间长了就容易变得难以维护。CommonsCollections的这一组Iterator为我们带来了便利。

五)代码样例
    1)Bag:

Java代码  收藏代码
  1. /** Book.java */   
  2. import org.apache.commons.lang.builder.ToStringBuilder;  
  3. import org.apache.commons.lang.builder.ToStringStyle;  
  4.    
  5. public class Book {  
  6.     private String name;  
  7.     private String isbn;  
  8.     private double retailPrice;  
  9.      
  10.     public Book() {}  
  11.     public Book(String name, String isbn, double retailPrice) {  
  12.         this.name = name;  
  13.         this.isbn = isbn;  
  14.         this.retailPrice = retailPrice;  
  15.     }  
  16.     public String toString() {  
  17.         return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)  
  18.         .append("name", name)  
  19.         .append("ISBN", isbn)  
  20.         .append("retailPrice", retailPrice)  
  21.         .toString();  
  22.     }  
  23.     public String getIsbn() {  
  24.         return isbn;  
  25.     }  
  26.     public void setIsbn(String isbn) {  
  27.         this.isbn = isbn;  
  28.     }  
  29.     public String getName() {  
  30.         return name;  
  31.     }  
  32.     public void setName(String name) {  
  33.         this.name = name;  
  34.     }  
  35.     public double getRetailPrice() {  
  36.         return retailPrice;  
  37.     }  
  38.     public void setRetailPrice(double retailPrice) {  
  39.         this.retailPrice = retailPrice;  
  40.     }  
  41.      
  42. }  
  43.    
  44. /** BagUsage.java */  
  45. import org.apache.commons.collections.Bag;  
  46. import org.apache.commons.collections.BagUtils;  
  47. import org.apache.commons.collections.bag.HashBag;  
  48. import org.apache.commons.lang.StringUtils;  
  49.    
  50. public class BagUsage {  
  51.    
  52.     public static void main(String[] args) {  
  53.         demoBagUsage();  
  54.     }  
  55.     public static void demoBagUsage() {  
  56.         System.out.println(StringUtils.center(" demoBagUsage "40"="));  
  57.    
  58.         // data setup  
  59.         Book book1 = new Book("Refactoring Workbook""7-5083-2208-8"29.8);  
  60.         Book book2 = new Book("J2EE Design Patterns""7-5083-3099-4"45);  
  61.         Book book3 = new Book("Agile Software Development""7-5083-1503-0"59);  
  62.    
  63.         // create a bag  
  64.         Bag myBag = BagUtils.typedBag(new HashBag(), Book.class);  
  65.         myBag.add(book1, 360); //Bag, add 360 book1s into myBag  
  66.         myBag.add(book2, 500); //Bag,add function  
  67.         myBag.add(book3, 170); //Bag,add function  
  68.    
  69.         // calculations for a bag  
  70.         double price1 = book1.getRetailPrice();  
  71.         double price2 = book2.getRetailPrice();  
  72.         double price3 = book3.getRetailPrice();  
  73.         int book1Count = myBag.getCount(book1);//the count should be 360  
  74.         int book2Count = myBag.getCount(book2);//the count should be 500  
  75.         int book3Count = myBag.getCount(book3);//the count should be 170  
  76.         double totalValue = (price1 * book1Count) + (price2 * book2Count)  
  77.                 + (price3 * book3Count);  
  78.    
  79.         // dispaly results  
  80.         System.out.println("There are " + book1Count + " copies of "  
  81.                 + book1.getName() + ".");  
  82.         System.out.println("There are " + book2Count + " copies of "  
  83.                 + book2.getName() + ".");  
  84.         System.out.println("There are " + book3Count + " copies of "  
  85.                 + book3.getName() + ".");  
  86.         System.out.println("The total value of these books is: " + totalValue);  
  87.         System.out.println();  
  88.    
  89.     }  
  90. }  

以下是运行结果:
============= demoBagUsage =============
There are 360 copies of Refactoring Workbook.
There are 500 copies of J2EE Design Patterns.
There are 170 copies of Agile Software Development.
The total value of these books is: 43258.0

    2)Buffer:

Java代码  收藏代码
  1. import java.util.Iterator;  
  2.    
  3. import org.apache.commons.collections.Buffer;  
  4. import org.apache.commons.collections.BufferUtils;  
  5. import org.apache.commons.collections.buffer.BoundedFifoBuffer;  
  6. import org.apache.commons.lang.StringUtils;  
  7.    
  8. public class BufferUsage {  
  9.     public static void main(String[] args) {  
  10.         demoBufferUsage();  
  11.     }  
  12.     public static void demoBufferUsage() {  
  13.    
  14.         System.out.println(StringUtils.center(" demoBagUsage "40"="));  
  15.    
  16.         // data setup  
  17.         Book book1 = new Book("Refactoring Workbook""7-5083-2208-8"29.8);  
  18.         Book book2 = new Book("J2EE Design Patterns""7-5083-3099-4"45);  
  19.         Book book3 = new Book("Agile Software Development""7-5083-1503-0"59);  
  20.         Book book4 = new Book("Professional JSP""7-5053-8005-2"100);  
  21.    
  22.         // create a Buffer  
  23.         Buffer buffer =  
  24.             BufferUtils.typedBuffer(new BoundedFifoBuffer(3), Book.class); //key line1  
  25.         buffer.add(book1);  
  26.         buffer.add(book2);  
  27.         buffer.add(book3);  
  28.         Book removed = (Book) buffer.remove();//key line2  
  29.         System.out.println("Removed:");  
  30.         System.out.println(removed);  
  31.         buffer.add(book4);//key line3  
  32.          
  33.         // get items in buffer  
  34.         for (int i = 0; i < 3; i++) {  
  35.             System.out.println(buffer.get());  
  36.             buffer.remove();  
  37.         }  
  38.         System.out.println(StringUtils.repeat("="40));  
  39.     }  
  40. }  

以下是运行结果:
============= demoBagUsage =============
Removed:
sean.study.commons.collections.Book@e09713[
  name=Refactoring Workbook
  ISBN=7-5083-2208-8
  retailPrice=29.8
]
Remaining:
sean.study.commons.collections.Book@e09713[
  name=J2EE Design Patterns
  ISBN=7-5083-3099-4
  retailPrice=45.0
]
sean.study.commons.collections.Book@47b480[
  name=Agile Software Development
  ISBN=7-5083-1503-0
  retailPrice=59.0
]
sean.study.commons.collections.Book@19b49e6[
  name=Professional JSP
  ISBN=7-5053-8005-2
  retailPrice=100.0
]
========================================

    3)Map:

Java代码  收藏代码
  1. import java.util.Date;  
  2. import java.util.HashMap;  
  3. import java.util.Map;  
  4.    
  5. import org.apache.commons.collections.BidiMap;  
  6. import org.apache.commons.collections.Factory;  
  7. import org.apache.commons.collections.MultiHashMap;  
  8. import org.apache.commons.collections.MultiMap;  
  9. import org.apache.commons.collections.bidimap.DualHashBidiMap;  
  10. import org.apache.commons.collections.map.LazyMap;  
  11. import org.apache.commons.lang.StringUtils;  
  12.    
  13. public class MapUsage {  
  14.     public static void main(String[] args) {  
  15.         demoBidiMap();  
  16.         demoMultiMap();  
  17.         demoLazyMap();  
  18.     }  
  19.     public static void demoBidiMap() {  
  20.         System.out.println(StringUtils.center(" demoBidiMap "40"="));  
  21.         BidiMap bidiMap = new DualHashBidiMap();  
  22.         bidiMap.put("BJ""Beijing");  
  23.         bidiMap.put("SH""Shanghai");  
  24.         bidiMap.put("GZ""Guangzhou");  
  25.         bidiMap.put("CD""Chengdu");  
  26.         System.out.println("Key-Value: BJ = " + bidiMap.get("BJ"));  
  27.         System.out.println("Value-Key: Chengdu = " + bidiMap.getKey("Chengdu"));  
  28.         System.out.println(StringUtils.repeat("="40));  
  29.     }  
  30.     public static void demoMultiMap() {  
  31.         System.out.println(StringUtils.center(" demoMultiMap "40"="));  
  32.         MultiMap multiMap = new MultiHashMap();  
  33.         multiMap.put("Sean""C/C++");  
  34.         multiMap.put("Sean""OO");  
  35.         multiMap.put("Sean""Java");  
  36.         multiMap.put("Sean"".NET");  
  37.         multiMap.remove("Sean""C/C++");  
  38.         System.out.println("Sean's skill set: " + multiMap.get("Sean"));  
  39.         System.out.println(StringUtils.repeat("="40));  
  40.     }  
  41.     public static void demoLazyMap() {  
  42.         System.out.println(StringUtils.center(" demoLazyMap "40"="));  
  43.         // borrowed from Commons Collection's Javadoc  
  44.         Factory factory = new Factory() {  
  45.             public Object create() {  
  46.                 return new Date();  
  47.             }  
  48.         };  
  49.         Map lazy = LazyMap.decorate(new HashMap(), factory);  
  50.         System.out.println(lazy.get("NOW"));  
  51.         System.out.println(StringUtils.repeat("="40));  
  52.     }  
  53. }  

以下是运行结果:
============= demoBidiMap ==============
Key-Value: BJ = Beijing
Value-Key: Chengdu = CD
========================================
============= demoMultiMap =============
Sean's skill set: [OO, Java, .NET]
========================================
============= demoLazyMap ==============
Wed Aug 03 12:44:56 CST 2005
========================================

    4)Comparator:

Java代码  收藏代码
  1. import org.apache.commons.lang.builder.ToStringBuilder;  
  2. import org.apache.commons.lang.builder.ToStringStyle;  
  3.    
  4. public class Issue {  
  5.     private long id;  
  6.     private String severity;  
  7.     private String owner;  
  8.      
  9.     public Issue() {}  
  10.     public Issue(long id, String severity, String owner) {  
  11.         this.id = id;  
  12.         this.severity = severity;  
  13.         this.owner = owner;  
  14.     }  
  15.     public String toString() {  
  16.         return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)  
  17.                 .append("id", id)  
  18.                 .append("severity", severity)  
  19.                 .append("owner", owner)  
  20.                 .toString();  
  21.     }  
  22.     public long getId() {  
  23.         return id;  
  24.     }  
  25.     public void setId(long id) {  
  26.         this.id = id;  
  27.     }  
  28.     public String getOwner() {  
  29.         return owner;  
  30.     }  
  31.     public void setOwner(String owner) {  
  32.         this.owner = owner;  
  33.     }  
  34.     public String getSeverity() {  
  35.         return severity;  
  36.     }  
  37.     public void setSeverity(String severity) {  
  38.         this.severity = severity;  
  39.     }  
  40. }  
  41.    
  42. /** ComparatorUsage.java */   
  43. import java.util.Arrays;  
  44. import java.util.Comparator;  
  45.    
  46. import org.apache.commons.beanutils.BeanComparator;  
  47. import org.apache.commons.collections.comparators.ComparatorChain;  
  48. import org.apache.commons.collections.comparators.FixedOrderComparator;  
  49. import org.apache.commons.lang.StringUtils;  
  50.    
  51. public class ComparatorUsage {  
  52.     public static void main(String[] args) {  
  53.         demoComparator();  
  54.     }  
  55.     public static void demoComparator() {  
  56.         System.out.println(StringUtils.center(" demoComparator "40"="));  
  57.         // data setup  
  58.         Issue[] issues = new Issue[] {  
  59.                 new Issue(15102"Major""John"),  
  60.                 new Issue(15103"Minor""Agnes"),  
  61.                 new Issue(15104"Critical""Bill"),  
  62.                 new Issue(15105"Major""John"),  
  63.                 new Issue(15106"Major""John"),  
  64.                 new Issue(15107"Critical""John"),  
  65.                 new Issue(15108"Major""Agnes"),  
  66.                 new Issue(15109"Minor""Julie"),  
  67.                 new Issue(15110"Major""Mary"),  
  68.                 new Issue(15111"Enhancement""Bill"),  
  69.                 new Issue(15112"Minor""Julie"),  
  70.                 new Issue(15113"Major""Julie")  
  71.         };  
  72.         // comparators setup  
  73.         String[] severityOrder = {"Critical""Major""Minor""Enhancement"};  
  74.         Comparator severityComparator = new FixedOrderComparator(severityOrder);//key line1  
  75.         ComparatorChain compChain = new ComparatorChain();//key line2  
  76.         compChain.addComparator(new BeanComparator("owner"));  
  77.         compChain.addComparator(new BeanComparator("severity", severityComparator));  
  78.         compChain.addComparator(new BeanComparator("id"));  
  79.         // sort and display  
  80.         Arrays.sort(issues, compChain);//key line3  
  81.         for (int i = 0; i < issues.length; i++) {  
  82.             System.out.println(issues[i]);  
  83.         }  
  84.         System.out.println(StringUtils.repeat("="40));  
  85.     }  
  86. }  

输出结果为:
============ demoComparator ============
Issue[id=15108,severity=Major,owner=Agnes]
Issue[id=15103,severity=Minor,owner=Agnes]
Issue[id=15104,severity=Critical,owner=Bill]
Issue[id=15111,severity=Enhancement,owner=Bill]
Issue[id=15107,severity=Critical,owner=John]
Issue[id=15102,severity=Major,owner=John]
Issue[id=15105,severity=Major,owner=John]
Issue[id=15106,severity=Major,owner=John]
Issue[id=15113,severity=Major,owner=Julie]
Issue[id=15109,severity=Minor,owner=Julie]
Issue[id=15112,severity=Minor,owner=Julie]
Issue[id=15110,severity=Major,owner=Mary]
========================================

    5)Predicate:

Java代码  收藏代码
  1. import org.apache.commons.collections.Predicate;  
  2. import org.apache.commons.collections.PredicateUtils;  
  3. import org.apache.commons.collections.functors.InstanceofPredicate;  
  4. import org.apache.commons.collections.functors.NotNullPredicate;  
  5. import org.apache.commons.lang.BooleanUtils;  
  6. import org.apache.commons.lang.StringUtils;  
  7.    
  8. public class PredicateUsage {  
  9.     public static void main(String[] args) {  
  10.         demoPredicates();  
  11.     }  
  12.     public static void demoPredicates() {  
  13.         System.out.println(StringUtils.center(" demoPredicates "40"="));  
  14.         Predicate p1 = new InstanceofPredicate(String.class); //key line1  
  15.         Predicate p2 = NotNullPredicate.getInstance(); //key line2  
  16.         Predicate p3 = new Predicate() { //key line3  
  17.             public boolean evaluate(Object obj) {  
  18.                 String str = (String) obj;  
  19.                 return StringUtils.isAlphanumeric(str)  
  20.                     && str.length() >= 6  
  21.                     && str.length() <= 10;  
  22.             }  
  23.         };  
  24.         Predicate p4 = PredicateUtils.allPredicate(new Predicate[]{p1, p2, p3}); //key line4                 
  25.         String input = "ABCD1234";  
  26.         Object[] raw = new Object[] {  
  27.             "Is '",  
  28.             input,  
  29.             "' a valid input? ",  
  30.             BooleanUtils.toStringYesNo(p4.evaluate(input)),  
  31.             "."  
  32.         };  
  33.         System.out.println(StringUtils.join(raw));  
  34.         System.out.println(StringUtils.repeat("="40));  
  35.     }  
  36. }  

输出结果如下:
============ demoPredicates ============
Is 'ABCD1234' a valid input? yes.
========================================

    6)Transformer:

Java代码  收藏代码
  1. /** Applicant.java */  
  2. package sean.study.commons.collections;  
  3.    
  4. import org.apache.commons.lang.builder.ToStringBuilder;  
  5. import org.apache.commons.lang.builder.ToStringStyle;  
  6.    
  7. public class Applicant {  
  8.     private String name;  
  9.     private int age;  
  10.     private String applyFor;  
  11.      
  12.     public Applicant() {}  
  13.     public Applicant(String name, int age, String applyFor) {  
  14.         this.name = name;  
  15.         this.age = age;  
  16.         this.applyFor = applyFor;  
  17.     }  
  18.     public String toString() {  
  19.         return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)  
  20.                 .append("name", name)  
  21.                 .append("age", age)  
  22.                 .append("applyFor", applyFor)  
  23.                 .toString();  
  24.     }  
  25.     public int getAge() {  
  26.         return age;  
  27.     }  
  28.     public void setAge(int age) {  
  29.         this.age = age;  
  30.     }  
  31.     public String getApplyFor() {  
  32.         return applyFor;  
  33.     }  
  34.     public void setApplyFor(String applyFor) {  
  35.         this.applyFor = applyFor;  
  36.     }  
  37.     public String getName() {  
  38.         return name;  
  39.     }  
  40.     public void setName(String name) {  
  41.         this.name = name;  
  42.     }  
  43. }  
  44.    
  45. /** Employee.java */  
  46. import java.util.Date;  
  47.    
  48. import org.apache.commons.lang.builder.ToStringBuilder;  
  49. import org.apache.commons.lang.builder.ToStringStyle;  
  50. import org.apache.commons.lang.time.DateFormatUtils;  
  51.    
  52. public class Employee {  
  53.     private String name;  
  54.     private int age;  
  55.     private Date dateJoined;  
  56.     private String grade;  
  57.     private double salary;  
  58.      
  59.     public Employee() {}  
  60.     public Employee(String name, int age, Date dateJoined, String grade, double salary) {  
  61.         this.name = name;  
  62.         this.age = age;  
  63.         this.dateJoined = dateJoined;  
  64.         this.grade = grade;  
  65.         this.salary = salary;  
  66.     }  
  67.     public String toString() {  
  68.         return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)  
  69.                 .append("name", name)  
  70.                 .append("age", age)  
  71.                 .append("dateJoined", DateFormatUtils.format(dateJoined, "yyyy-MM-dd"))  
  72.                 .append("grade", grade)  
  73.                 .append("salary", salary)  
  74.                 .toString();  
  75.     }  
  76.     public int getAge() {  
  77.         return age;  
  78.     }  
  79.     public void setAge(int age) {  
  80.         this.age = age;  
  81.     }  
  82.     public Date getDateJoined() {  
  83.         return dateJoined;  
  84.     }  
  85.     public void setDateJoined(Date dateJoined) {  
  86.         this.dateJoined = dateJoined;  
  87.     }  
  88.     public String getGrade() {  
  89.         return grade;  
  90.     }  
  91.     public void setGrade(String grade) {  
  92.         this.grade = grade;  
  93.     }  
  94.     public String getName() {  
  95.         return name;  
  96.     }  
  97.     public void setName(String name) {  
  98.         this.name = name;  
  99.     }  
  100.     public double getSalary() {  
  101.         return salary;  
  102.     }  
  103.     public void setSalary(double salary) {  
  104.         this.salary = salary;  
  105.     }  
  106. }  
  107.    
  108. /** TransformerUsage.java */  
  109. import java.util.Arrays;  
  110. import java.util.Collection;  
  111. import java.util.Date;  
  112. import java.util.Iterator;  
  113. import java.util.List;  
  114.    
  115. import org.apache.commons.collections.CollectionUtils;  
  116. import org.apache.commons.collections.Predicate;  
  117. import org.apache.commons.collections.Transformer;  
  118. import org.apache.commons.collections.functors.SwitchTransformer;  
  119. import org.apache.commons.lang.StringUtils;  
  120.    
  121. public class TransformerUsage {  
  122.     public static void main(String[] args) {  
  123.         demoTransformerUsage();  
  124.     }  
  125.     public static void demoTransformerUsage() {  
  126.         System.out.println(StringUtils.center(" demoTransformerUsage "40"="));  
  127.    
  128.         // data setup  
  129.         Applicant[] applicants = new Applicant[] {  
  130.             new Applicant("Tony"26"Developer"),  
  131.             new Applicant("Michelle"24"Tester"),  
  132.             new Applicant("Jack"28"Project Manager")  
  133.         };  
  134.         List appList = Arrays.asList(applicants);  
  135.          
  136.         // predicate setup  
  137.         Predicate isDeveloper = new Predicate() {  
  138.             public boolean evaluate(Object obj) {  
  139.                 Applicant app = (Applicant) obj;  
  140.                 return "Developer".equalsIgnoreCase(app.getApplyFor());  
  141.             }  
  142.         };  
  143.         Predicate isTester = new Predicate() {  
  144.             public boolean evaluate(Object obj) {  
  145.                 Applicant app = (Applicant) obj;  
  146.                 return "Tester".equalsIgnoreCase(app.getApplyFor());  
  147.             }  
  148.         };  
  149.         Predicate isPM = new Predicate() {  
  150.             public boolean evaluate(Object obj) {  
  151.                 Applicant app = (Applicant) obj;  
  152.                 return "Project Manager".equalsIgnoreCase(app.getApplyFor());  
  153.             }  
  154.         };  
  155.         Predicate[] checkApplyFor = new Predicate[] {  
  156.             isDeveloper,  
  157.             isTester,  
  158.             isPM  
  159.         };  
  160.          
  161.         // transformer setup  
  162.         Transformer developerTransformer = new Transformer() {  
  163.             public Object transform(Object obj) {  
  164.                 Applicant app = (Applicant) obj;  
  165.                 return new Employee(  
  166.                     app.getName(), app.getAge(), new Date(), "E4"2000  
  167.                 );  
  168.             }  
  169.         };  
  170.         Transformer testerTransformer = new Transformer() {  
  171.             public Object transform(Object obj) {  
  172.                 Applicant app = (Applicant) obj;  
  173.                 return new Employee(  
  174.                     app.getName(), app.getAge(), new Date(), "E4"2000  
  175.                 );  
  176.             }  
  177.         };  
  178.         Transformer pmTransformer = new Transformer() {  
  179.             public Object transform(Object obj) {  
  180.                 Applicant app = (Applicant) obj;  
  181.                 return new Employee(  
  182.                     app.getName(), app.getAge(), new Date(), "E5"3000  
  183.                 );  
  184.             }  
  185.         };  
  186.         Transformer[] transformers = new Transformer[] {  
  187.             developerTransformer,  
  188.             testerTransformer,  
  189.             pmTransformer  
  190.         };  
  191.          
  192.         // transform  
  193.         Transformer employTransformer = new SwitchTransformer(  
  194.             checkApplyFor, transformers, null  
  195.         );  
  196.         Collection employed = CollectionUtils.collect(appList, employTransformer);  
  197.          
  198.         // output  
  199.         System.out.println("Applicants: ");  
  200.         Iterator iter1 = appList.iterator();  
  201.         while (iter1.hasNext()) {  
  202.             System.out.println(iter1.next());  
  203.         }  
  204.         System.out.println("Employed: ");  
  205.         Iterator iter2 = employed.iterator();  
  206.         while (iter2.hasNext()) {  
  207.             System.out.println(iter2.next());  
  208.         }  
  209.    
  210.         System.out.println(StringUtils.repeat("="40));  
  211.     }  
  212.    
  213. }  

以下是运行结果:
========= demoTransformerUsage =========
Applicants:
Applicant[name=Tony,age=26,applyFor=Developer]
Applicant[name=Michelle,age=24,applyFor=Tester]
Applicant[name=Jack,age=28,applyFor=Project Manager]
Employed:
Employee[name=Tony,age=26,dateJoined=2005-08-05,grade=E4,salary=2000.0]
Employee[name=Michelle,age=24,dateJoined=2005-08-05,grade=E4,salary=2000.0]
Employee[name=Jack,age=28,dateJoined=2005-08-05,grade=E5,salary=3000.0]
========================================

    7)Closure:

Java代码  收藏代码
  1. import java.util.Arrays;  
  2. import java.util.Collection;  
  3. import java.util.Date;  
  4. import java.util.Iterator;  
  5.    
  6. import org.apache.commons.collections.Closure;  
  7. import org.apache.commons.collections.CollectionUtils;  
  8. import org.apache.commons.lang.StringUtils;  
  9.    
  10. public class ClosureUsage {  
  11.    
  12.     public static void main(String[] args) {  
  13.         demoClosureUsage();  
  14.     }  
  15.      
  16.     public static void demoClosureUsage() {  
  17.    
  18.         System.out.println(StringUtils.center(" demoClosureUsage "40"="));  
  19.          
  20.         // data setup  
  21.         Employee[] employees = new Employee[] {  
  22.             new Employee("Tony"26new Date(), "E4"2000),  
  23.             new Employee("Michelle"24new Date(), "E4"2000),  
  24.             new Employee("Jack"28new Date(), "E5"3000)  
  25.         };  
  26.         Collection empColl = Arrays.asList(employees);  
  27.         printColl("Before salary increase:", empColl);  
  28.          
  29.         // closure setup  
  30.         Closure salaryIncreaseClosure = new Closure() {//key line1  
  31.             public void execute(Object obj) {  
  32.                 Employee emp = (Employee) obj;  
  33.                 emp.setSalary(emp.getSalary() * 1.20);  
  34.             }  
  35.         };  
  36.          
  37.         // salary increase  
  38.         CollectionUtils.forAllDo(empColl, salaryIncreaseClosure);//key line2  
  39.         printColl("After salary increase:", empColl);  
  40.    
  41.         System.out.println(StringUtils.repeat("="40));  
  42.     }  
  43.      
  44.     public static void printColl(String label, Collection c) {  
  45.         if (StringUtils.isNotBlank(label)) {  
  46.             System.out.println(label);  
  47.         }  
  48.         Iterator iter = c.iterator();  
  49.         while (iter.hasNext()) {  
  50.             System.out.println(iter.next());  
  51.         }  
  52.     }  
  53. }  

以下是运行结果:
=========== demoClosureUsage ===========
Before salary increase:
Employee[name=Tony,age=26,dateJoined=2005-08-05,grade=E4,salary=2000.0]
Employee[name=Michelle,age=24,dateJoined=2005-08-05,grade=E4,salary=2000.0]
Employee[name=Jack,age=28,dateJoined=2005-08-05,grade=E5,salary=3000.0]
After salary increase:
Employee[name=Tony,age=26,dateJoined=2005-08-05,grade=E4,salary=2400.0]
Employee[name=Michelle,age=24,dateJoined=2005-08-05,grade=E4,salary=2400.0]
Employee[name=Jack,age=28,dateJoined=2005-08-05,grade=E5,salary=3600.0]
========================================

    8)Iterator:

Java代码  收藏代码
  1. import java.util.Arrays;  
  2. import java.util.Iterator;  
  3. import java.util.List;  
  4.    
  5. import org.apache.commons.collections.Predicate;  
  6. import org.apache.commons.collections.iterators.ArrayListIterator;  
  7. import org.apache.commons.collections.iterators.FilterIterator;  
  8. import org.apache.commons.collections.iterators.LoopingIterator;  
  9. import org.apache.commons.lang.StringUtils;  
  10.    
  11. public class IteratorUsage {  
  12.    
  13.     public static void main(String[] args) {  
  14.         demoIteratorUsage();  
  15.     }  
  16.      
  17.     public static void demoIteratorUsage() {  
  18.    
  19.         System.out.println(StringUtils.center(" demoClosureUsage "40"="));  
  20.          
  21.         // data setup  
  22.         String[] weekDays = {  
  23.             "Monday""Tuesday""Wednesday",  
  24.             "Thursday""Friday""Saturday""Sunday"  
  25.         };  
  26.         List weekDayList = Arrays.asList(weekDays);  
  27.          
  28.         // workdays  
  29.         Iterator iter1 = new ArrayListIterator(weekDays, 05);//key line1  
  30.         printColl("Partial:", iter1, 5);  
  31.          
  32.         // loop  
  33.         Iterator iter2 = new LoopingIterator(weekDayList);//key line2  
  34.         printColl("Loop:", iter2, 10);  
  35.          
  36.         // looping workdays  
  37.         Predicate notWeekendPredicate = new Predicate() {  
  38.             public boolean evaluate(Object obj) {  
  39.                 String str = (String) obj;  
  40.                 if ("Saturday".equalsIgnoreCase(str)) {  
  41.                     return false;  
  42.                 }  
  43.                 if ("Sunday".equalsIgnoreCase(str)) {  
  44.                     return false;  
  45.                 }  
  46.                 return true;  
  47.             }  
  48.         };  
  49.         Iterator iter3 = new FilterIterator(//key line3  
  50.             new LoopingIterator(weekDayList),  
  51.             notWeekendPredicate  
  52.         );  
  53.         printColl("No Weekends loop:", iter3, 12);  
  54.          
  55.         System.out.println(StringUtils.repeat("="40));  
  56.    
  57.     }  
  58.      
  59.     public static void printColl(String label, Iterator iter, int maxCount) {  
  60.         if (StringUtils.isNotBlank(label)) {  
  61.             System.out.println(label);  
  62.         }  
  63.         int i = 0;  
  64.         while (iter.hasNext() && i < maxCount) {  
  65.             System.out.println("# " + iter.next() + " #");  
  66.             i++;  
  67.         }  
  68.     }  
  69.    
  70. }  

运行结果如下:
=========== demoClosureUsage ===========
Partial:
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
Loop:
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
# Saturday #
# Sunday #
# Monday #
# Tuesday #
# Wednesday #
No Weekends loop:
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
# Monday #
# Tuesday #
# Wednesday #
# Thursday #
# Friday #
# Monday #
# Tuesday #
========================================

抱歉!评论已关闭.