带你领略 Google Collections 2

原贴地址:

http://jubin2002.javaeye.com/blog/471698

上篇讲到google collections的几个比较主要的点,今天我们来看看其提供的几个小的但是相当有用的东西。

1,Preconditions

Preconditions 提供了状态校验的方法。

Before:

Java代码
  1. public DeliverycreateDelivery(Orderorder,UserdeliveryPerson){
  2. if (order.getAddress()== null ){
  3. throw new NullPointerException( "orderaddress" );
  4. }
  5. if (!workSchedule.isOnDuty(deliveryPerson,order.getArrivalTime())){
  6. throw new IllegalArgumentException(
  7. String.format("%sisnotondutyfor%s" ,deliveryPerson,order));
  8. }
  9. return new RealDelivery(order,deliveryPerson);
  10. }

After:

Java代码
  1. public DeliverycreateDelivery(Orderorder,UserdeliveryPerson){
  2. Preconditions.checkNotNull(order.getAddress(),"orderaddress" );
  3. Preconditions.checkArgument(
  4. workSchedule.isOnDuty(deliveryPerson,order.getArrivalTime()),
  5. "%sisnotondutyfor%s" ,deliveryPerson,order);
  6. return new RealDelivery(order,deliveryPerson);
  7. }

2,Iterables.getOnlyElement

Iterables.getOnlyElement 确保你的集合或者迭代器包含了刚好一个元素并且返回该元素。如果他包含0和2+元素,它会抛出RuntimeException。一般在单元测试中使用。

Before:

Java代码
  1. public void testWorkSchedule(){
  2. workSchedule.scheduleUserOnDuty(jesse,mondayAt430pm,mondayAt1130pm);
  3. Set<User>usersOnDuty=workSchedule.getUsersOnDuty(mondayAt800pm);
  4. assertEquals(1 ,usersOnDuty.size());
  5. assertEquals(jesse,usersOnDuty.iterator().next());
  6. }

After:

Java代码
  1. public void testWorkSchedule(){
  2. workSchedule.scheduleUserOnDuty(jesse,mondayAt430pm,mondayAt1130pm);
  3. Set<User>usersOnDuty=workSchedule.getUsersOnDuty(mondayAt800pm);
  4. assertEquals(jesse,Iterables.getOnlyElement(usersOnDuty));
  5. }

Iterables.getOnlyElement比Set.iterator().getNext()和List.get(0)描述的更为直接。


3,Objects.equal

Objects.equal(Object,Object) and Objects.hashCode(Object...)提供了内建的null处理,能使你实现equals()hashCode()更加简单。

Before:

Java代码
  1. public boolean equals(Objecto){
  2. if (o instanceof Order){
  3. Orderthat=(Order)o;
  4. return (address!= null
  5. ?address.equals(that.address)
  6. :that.address==null )
  7. &&(targetArrivalDate!=null
  8. ?targetArrivalDate.equals(that.targetArrivalDate)
  9. :that.targetArrivalDate==null )
  10. &&lineItems.equals(that.lineItems);
  11. }else {
  12. return false ;
  13. }
  14. }
  15. public int hashCode(){
  16. int result= 0 ;
  17. result=31 *result+(address!= null ?address.hashCode(): 0 );
  18. result=31 *result+(targetArrivalDate!= null ?targetArrivalDate.hashCode(): 0 );
  19. result=31 *result+lineItems.hashCode();
  20. return result;
  21. }

After:

Java代码
  1. public boolean equals(Objecto){
  2. if (o instanceof Order){
  3. Orderthat=(Order)o;
  4. return Objects.equal(address,that.address)
  5. &&Objects.equal(targetArrivalDate,that.targetArrivalDate)
  6. &&Objects.equal(lineItems,that.lineItems);
  7. }else {
  8. return false ;
  9. }
  10. }
  11. public int hashCode(){
  12. return Objects.hashCode(address,targetArrivalDate,lineItems);
  13. }

4,Iterables.concat()

Iterables.concat() 连结多种集合 (比如ArrayList和HashSet) 以至于你能在一行代码里遍历他们:

Before:

Java代码
  1. public boolean orderContains(Productproduct){
  2. List<LineItem>allLineItems=new ArrayList<LineItem>();
  3. allLineItems.addAll(getPurchasedItems());
  4. allLineItems.addAll(getFreeItems());
  5. for (LineItemlineItem:allLineItems){
  6. if (lineItem.getProduct()==product){
  7. return true ;
  8. }
  9. }
  10. return false ;
  11. }

After:

Java代码
  1. public boolean orderContains(Productproduct){
  2. for (LineItemlineItem:Iterables.concat(getPurchasedItems(),getFreeItems())){
  3. if (lineItem.getProduct()==product){
  4. return true ;
  5. }
  6. }
  7. return false ;
  8. }

5,Join

Join 是用分隔符分割字符串变得非常容易。

Before:

Java代码
  1. public class ShoppingList{
  2. private List<Item>items=...;
  3. ...
  4. public StringtoString(){
  5. StringBuilderstringBuilder=new StringBuilder();
  6. for (Iterator<Item>s=items.iterator();s.hasNext();){
  7. stringBuilder.append(s.next());
  8. if (s.hasNext()){
  9. stringBuilder.append("and" );
  10. }
  11. }
  12. return stringBuilder.toString();
  13. }
  14. }

After:

Java代码
  1. public class ShoppingList{
  2. private List<Item>items=...;
  3. ...
  4. public StringtoString(){
  5. return Joiner.on( "and" ).join(items);
  6. }
  7. }

6,Maps, Sets and Lists

泛型是好的,不过他们有些过于罗嗦。

Before:

Java代码
  1. Map<CustomerId,BillingOrderHistory>customerOrderHistoryMap
  2. =new HashMap<CustomerId,BillingOrderHistory>();

After:

Java代码
  1. Map<CustomerId,BillingOrderHistory>customerOrderHistoryMap
  2. =Maps.newHashMap();

Maps, Sets and Lists 包含了工厂方法来创建集合对象。

另一个例子,Before:

Java代码
  1. Set<String>workdays= new LinkedHashSet<String>();
  2. workdays.add("Monday" );
  3. workdays.add("Tuesday" );
  4. workdays.add("Wednesday" );
  5. workdays.add("Thursday" );
  6. workdays.add("Friday" );

OR:

Java代码
  1. Set<String>workdays= new LinkedHashSet<String>(
  2. Arrays.asList("Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" ));

After:

Java代码
  1. Set<String>workdays=Sets.newLinkedHashSet(
  2. "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" );

Google Collections 对于Maps, Sets, Lists, Multimaps, Multisets 都提供了工厂方法 。

你可能感兴趣的:(Google,Blog,单元测试)