`
jubin2002
  • 浏览: 39576 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

带你领略 Google Collections 2

阅读更多

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

 

1,Preconditions

 

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

 

Before:

public Delivery createDelivery(Order order, User deliveryPerson) {
    
    if(order.getAddress() == null) {
        throw new NullPointerException("order address");
    }
    
    if(!workSchedule.isOnDuty(deliveryPerson, order.getArrivalTime())) {
        throw new IllegalArgumentException(
            String.format("%s is not on duty for %s", deliveryPerson, order));
    }

    return new RealDelivery(order, deliveryPerson);
}

 After:

public Delivery createDelivery(Order order, User deliveryPerson) {
    Preconditions.checkNotNull(order.getAddress(), "order address");
    Preconditions.checkArgument(
        workSchedule.isOnDuty(deliveryPerson, order.getArrivalTime()),
            "%s is not on duty for %s", deliveryPerson, order);

    return new RealDelivery(order, deliveryPerson);
}
 

2,Iterables.getOnlyElement

 

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

 

Before:

public void testWorkSchedule() {
    workSchedule.scheduleUserOnDuty(jesse, mondayAt430pm, mondayAt1130pm);

    Set<User> usersOnDuty = workSchedule.getUsersOnDuty(mondayAt800pm);
    assertEquals(1, usersOnDuty.size());
    assertEquals(jesse, usersOnDuty.iterator().next());
}

 After:

public void testWorkSchedule() {
    workSchedule.scheduleUserOnDuty(jesse, mondayAt430pm, mondayAt1130pm);

    Set<User> usersOnDuty = workSchedule.getUsersOnDuty(mondayAt800pm);
    assertEquals(jesse, Iterables.getOnlyElement(usersOnDuty));
}

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


3,Objects.equal

 

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

 

Before:

public boolean equals(Object o) {
    if (o instanceof Order) {
      Order that = (Order)o;

      return (address != null 
              ? address.equals(that.address) 
              : that.address == null) 
          && (targetArrivalDate != null 
              ? targetArrivalDate.equals(that.targetArrivalDate) 
              : that.targetArrivalDate == null)
          && lineItems.equals(that.lineItems);
    } else {
      return false;
    }
}

public int hashCode() {
    int result = 0;
    result = 31 * result + (address != null ? address.hashCode() : 0);
    result = 31 * result + (targetArrivalDate != null ? targetArrivalDate.hashCode() : 0);
    result = 31 * result + lineItems.hashCode();
    return result;
}

 After:

public boolean equals(Object o) {
    if (o instanceof Order) {
      Order that = (Order)o;

      return Objects.equal(address, that.address)
          && Objects.equal(targetArrivalDate, that.targetArrivalDate)
          && Objects.equal(lineItems, that.lineItems);
    } else {
      return false;
    }
}

public int hashCode() {
    return Objects.hashCode(address, targetArrivalDate, lineItems);
}

 

4,Iterables.concat()

 

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

 

Before:

public boolean orderContains(Product product) {
    List<LineItem> allLineItems = new ArrayList<LineItem>();
    allLineItems.addAll(getPurchasedItems());
    allLineItems.addAll(getFreeItems());

    for (LineItem lineItem : allLineItems) {
      if (lineItem.getProduct() == product) {
        return true;
      }
    }

    return false;
}

 After:

public boolean orderContains(Product product) {
    for (LineItem lineItem : Iterables.concat(getPurchasedItems(), getFreeItems())) {
      if (lineItem.getProduct() == product) {
        return true;
      }
    }

    return false;
}

 

5,Join

 

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

 

Before:

public class ShoppingList {
  private List<Item> items = ...;

  ...

  public String toString() {
    StringBuilder stringBuilder = new StringBuilder();
    for (Iterator<Item> s = items.iterator(); s.hasNext(); ) {
      stringBuilder.append(s.next());
      if (s.hasNext()) {
        stringBuilder.append(" and ");
      }
    }
    return stringBuilder.toString();
  }
}
 

After:

public class ShoppingList {
  private List<Item> items = ...;

  ...

  public String toString() {
    return Joiner.on(" and ").join(items);
  }
}

 

6,Maps, Sets and Lists

 

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

 

Before:

Map<CustomerId, BillingOrderHistory> customerOrderHistoryMap 
    = new HashMap<CustomerId, BillingOrderHistory>();

 After:

Map<CustomerId, BillingOrderHistory> customerOrderHistoryMap 
    = Maps.newHashMap();

 

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

 

另一个例子,Before:

Set<String> workdays = new LinkedHashSet<String>();
workdays.add("Monday");
workdays.add("Tuesday");
workdays.add("Wednesday");
workdays.add("Thursday");
workdays.add("Friday");

 OR:

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

 After:

Set<String> workdays = Sets.newLinkedHashSet(
  "Monday", "Tuesday", "Wednesday", "Thursday", "Friday");

 

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

分享到:
评论

相关推荐

    google-collections-1.0.rar

    google公共工具类;google collections是google的工程师利用传说中的“20%时间”开发的集合库,它是对java.util的扩展,提供了很多实用的类来简化代码。google collections使用了范型,所以要求jdk1.5以上。

    google-collections-1.0-rc2.jar

    google-collections-1.0-rc2.jar 的jar包,放心使用。

    google-collections-1.0-sources.jar

    google-collections-1.0-sources.jar

    commons-collections.jar

    commons-collections-20040616.jar, commons-collections-3.2-osgi.jar, commons-collections-3.2-sources.jar, commons-collections-3.2.1.jar, commons-collections-3.2.2-javadoc.jar, commons-collections-3.2.2...

    google-collections

    oogle collections是google的工程师利用传说中的“20%时间”开发的集合库,它是对java.util的扩展,提供了很多实用的类来简化代码。google collections使用了范型,所以要求jdk1.5以上。它的作者没有像apache ...

    Google Collections包

    Java的集合框架是Java类库当中使用频率最高的部分之一,而Google Collections库是由Google基于Java5.0 Collections Framework开发的一套新的Java集合框架,提供一些高级集合操作的API。

    google-collections-1.0-rc1.jar

    google-collections-1.0-rc1.jar

    google-collections jar包

    import com.google.common.collect.Maps 所需要的jar包

    commons-collections-3.2.2-API文档-中文版.zip

    赠送jar包:commons-collections-3.2.2.jar; 赠送原API文档:commons-collections-3.2.2-javadoc.jar; 赠送源代码:commons-collections-3.2.2-sources.jar; 赠送Maven依赖信息文件:commons-collections-3.2.2....

    Google Collections 源代码和API文档

    Google Collections是Google公司开发的常用工具库,包括对字符串,文件操作,数据结构和并发程序开发的支持。它比Apache Commons Collections提供了更多更强大的函数,使得程序编写更加简洁,不易产生错误。 这个...

    commons-collections4-4.1-API文档-中文版.zip

    赠送jar包:commons-collections4-4.1.jar; 赠送原API文档:commons-collections4-4.1-javadoc.jar; 赠送源代码:commons-collections4-4.1-sources.jar; 赠送Maven依赖信息文件:commons-collections4-4.1.pom;...

    Collections

    Collections 中部分方法详解如GridView中Collections.swap

    collections-generic-4.01_and_looks-2.1.4

    该文件里包含两个.jar包: collections-generic-4.01.jar和looks-2.1.4.jar, 引入collections-generic-4.01.jar: 右击工程--》Build path ——》Add External JAR--&gt;选中collections-generic-4.01.jar --》OK 在源...

    Google-Guava-Collections-使用介绍

    commons-collections4-4.4-API文档-中英对照版.zip

    赠送jar包:commons-collections4-4.4.jar; 赠送原API文档:commons-collections4-4.4-javadoc.jar; 赠送源代码:commons-collections4-4.4-sources.jar; 赠送Maven依赖信息文件:commons-collections4-4.4.pom;...

    commons-collections4-4.4-API文档-中文版.zip

    赠送jar包:commons-collections4-4.4.jar; 赠送原API文档:commons-collections4-4.4-javadoc.jar; 赠送源代码:commons-collections4-4.4-sources.jar; 赠送Maven依赖信息文件:commons-collections4-4.4.pom;...

    commons-collections-3.2.2-API文档-中英对照版.zip

    赠送jar包:commons-collections-3.2.2.jar; 赠送原API文档:commons-collections-3.2.2-javadoc.jar; 赠送源代码:commons-collections-3.2.2-sources.jar; 赠送Maven依赖信息文件:commons-collections-3.2.2....

    collections4/collections15 jar

    在Java代码运行时报ClassNotDef 缺少包为collcetions4 或者collections15

    google-collections-1.0.jar

    google-collections-1.0.jar

    commons-collections-2.0.jar

    commons-collections-2.0.jar

Global site tag (gtag.js) - Google Analytics