Guava-Collections-Utility Classes

Guava提供了比JDK集合工具类Collections更多,更方便的操作集合的方法

以下是相应接口所对应的工具类

Interface JDK or Guava? Corresponding Guava utility class
Collection JDK Collections2 (avoiding conflict with java.util.Collections)
List JDK Lists
Set JDK Sets
SortedSet JDK Sets
Map JDK Maps
SortedMap JDK Maps
Queue JDK Queues
Multiset Guava Multisets
Multimap Guava Multimaps
BiMap Guava Maps
Table Guava Tables

在JDK7以前,我们经常这样写

  @Test
    public void ListsArraysUtilsTest() {
        List<Book> books = new ArrayList<Book>();
        //jdk7以后我们可以,(—这里我未测试通过!—),倒是new ArrayList()是可以的
        List<String> bookList = new ArrayList<>();
        List<Book> books1 = Lists.newArrayList();
        Map<Integer, Book> bookMap = Maps.newHashMap();
        //就以上这些,根本不足以体现出Guava的集合工具类的优势,真正的优势在于Guava,提供了快速初始化
        List<String> slist = Lists.newArrayList("first","second","third");
        //这点在做测试的时候能够特别快速地构建出一个包含初始数据的List或Map

        //此外,集合工具类,还能初始化集合的容量,有助于提高性能
        List<Book> exactly100 = Lists.newArrayListWithCapacity(100);
        List<Book> approx100 = Lists.newArrayListWithExpectedSize(100);
        Set<Book> approx100Set = Sets.newHashSetWithExpectedSize(100);

        //使用 static import 后能直接使用这些方法
    }

 

Iterables

  Guava更倾向于提供Iterable而不是Collection,在google 你会经常遇到一些情况,一个“集合”它不是存储在内存中,而是分布在不同的数据库或者说是数据中心中,并且不支持想 Collections 的 size()方法。

  所以如果你想找一些所有集合都支持的方法,那么你要从Iterable里面找,而不是Collection。另外,大部分的Iterables 都有与之相对应版本的Iterators,Iterators带有无参的构造方法。

  在Iterable中,绝大多数的操作为  lazy  操作。按需加载。

  Guava 12后(目前稳定版为15), Iterables有了个增强类FluentIterable

以下列举了一些常用的操作 

 

Method Description See Also
concat(Iterable<Iterable>) Returns a lazy view of the concatenation of several iterables. concat(Iterable...)
frequency(Iterable, Object) Returns the number of occurrences of the object. Compare Collections.frequency(Collection, Object); see Multiset
partition(Iterable, int) Returns an unmodifiable view of the iterable partitioned into chunks of the specified size. Lists.partition(List, int)paddedPartition(Iterable, int)
getFirst(Iterable, T default) Returns the first element of the iterable, or the default value if empty. Compare Iterable.iterator().next()
FluentIterable.first()
getLast(Iterable) Returns the last element of the iterable, or fails fast with a NoSuchElementExceptionif it's empty. getLast(Iterable, T default)
FluentIterable.last()
elementsEqual(Iterable, Iterable) Returns true if the iterables have the same elements in the same order. Compare List.equals(Object)
unmodifiableIterable(Iterable) Returns an unmodifiable view of the iterable. CompareCollections.unmodifiableCollection(Collection)
limit(Iterable, int) Returns an Iterable returning at most the specified number of elements. FluentIterable.limit(int)
getOnlyElement(Iterable) Returns the only element in Iterable. Fails fast if the iterable is empty or has multiple elements. getOnlyElement(Iterable, T default)

 

   @Test
    public void IterablesTest() {
        Iterable<Integer> concatenated = Iterables.concat(
                Ints.asList(1, 2, 3),
                Ints.asList(4, 5, 6),
                Ints.asList(2, 3, 9));
        System.out.println(Iterables.frequency(concatenated, 9));
    }

   

 

如上图,java中的Iterable是一个Interface,在Collection之上,Iterables是Guava的一个工具类

java.lang.Iterable

java.util.Iterator

 

Collection-Like(类似于Collection)

一般来说,collection 作用的对象为另一个collection ,而不是Iterable。

Iterables工具类的以下方法,各自对应了Collection接口的方法

 

Method Analogous Collection method FluentIterable equivalent
addAll(Collection addTo, Iterable toAdd) Collection.addAll(Collection)  
contains(Iterable, Object) Collection.contains(Object) FluentIterable.contains(Object)
removeAll(Iterable removeFrom, Collection toRemove) Collection.removeAll(Collection)  
retainAll(Iterable removeFrom, Collection toRetain) Collection.retainAll(Collection)  
size(Iterable) Collection.size() FluentIterable.size()
toArray(Iterable, Class) Collection.toArray(T[]) FluentIterable.toArray(Class)
isEmpty(Iterable) Collection.isEmpty() FluentIterable.isEmpty()
get(Iterable, int) List.get(int) FluentIterable.get(int)
toString(Iterable) Collection.toString() FluentIterable.toString()

 

 

FluentIterable

FluentIterable这个增强型接口也提供了一些更方便的方法

 

Lists,Sets,Maps,Queue

这些工具类提供了很多对操作List,set,map,queue等对象有用的工具方法。

每个工具类都提供了一堆 Static Factories 用于初始化集合对象。这里进队Lists进行举例。除此之外,每个集合工具对不同集合不同的操作可参考文档。 

Lists provides the following static factory methods:

Implementation Factories
ArrayList basicwith elementsfrom Iterablewith exact capacitywith expected sizefrom Iterator
LinkedList basicfrom Iterable

Sets provides the following static factory methods:

Implementation Factories
HashSet basicwith elementsfrom Iterablewith expected sizefrom Iterator
LinkedHashSet basicfrom Iterablewith expected size
TreeSet basicwith Comparatorfrom Iterable

 Maps provides the following static factory methods.

Implementation Factories
HashMap basicfrom Mapwith expected size
LinkedHashMap basicfrom Map
TreeMap basicfrom Comparatorfrom SortedMap
EnumMap from Classfrom Map
ConcurrentMap (supporting all operations) basic
IdentityHashMap basic

 

 例子: 

    @Test
    public void ListsUtilsTest() {
        Iterable<Integer> concatenated = Iterables.concat(
                Ints.asList(1, 2, 3),
                Ints.asList(4, 5, 6),
                Ints.asList(2, 3, 9));
        List<Integer> list = Ints.asList(1, 23, 4, 5, 6);
        //basic
        List<Integer> list_basic = Lists.newArrayList();
        // from iterable
        List<Integer> list_from_iterable = Lists.newArrayList(concatenated);
        // ...others

    }

 

 

 

Multisets,Multimaps,Tables

普通的Collection在调用containsAll的时候,仅判断集合中是否存在该元素,而不去判断该元素在集合中存在的数目,以上三个工具类提供了丰富的方法来解决这些问题

Method Explanation Difference from Collection method
containsOccurrences(Multiset sup, Multiset sub) Returns true if sub.count(o) <= super.count(o) for all o. Collection.containsAll ignores counts, and only tests whether elements are contained at all.
removeOccurrences(Multiset removeFrom, Multiset toRemove) Removes one occurrence in removeFrom for each occurrence of an element in toRemove. Collection.removeAll removes all occurences of any element that occurs even once in toRemove.
retainOccurrences(Multiset removeFrom, Multiset toRetain) Guarantees that removeFrom.count(o) <= toRetain.count(o) for all o. Collection.retainAll keeps all occurrences of elements that occur even once in toRetain.
intersection(Multiset, Multiset) Returns a view of the intersection of two multisets; a nondestructive alternative to retainOccurrences. Has no analogue

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2013-10-12 16:04  jake-  阅读(657)  评论(0编辑  收藏  举报