Guava学习——集合工具

来源:互联网 发布:java培训多少 编辑:程序博客网 时间:2024/06/07 00:22

Guava提供的集合
Multiset:一个扩展来设置界面,允许重复的元素
Multimap:一个扩展映射接口,以便其键可一次被映射多个值
BiMap:一个扩展来映射接口,支持反向操作(位图)
Table:表代表一个特殊的图,其中两个键可以在组合的方式被指定为单个值

Multiset

Multiset接口扩展设置有重复的值,并提供了各种实用的方法来处理这样的元素在集合中出现

//接口的声明@GwtCompatiblepublic interface Multiset<E>   extends Collection<E>

几个好用的方法

//添加一个出现的指定元素这个multiset。boolean add(E element)//增加大量的元素到这个multiset。   int add(E element, int occurrences)//确定此多集是否包含指定的元素。   boolean contains(Object element)//返回true,如果这个多集至少包含一个出现的指定集合中的所有元素  boolean containsAll(Collection<?> elements)//返回出现的元素的在该multiset的数目(元素的数量)int count(Object element)//返回集包含在此多集不同的元素。Set<E> elementSet()//返回此多集的内容的视图,分组在Multiset.Entry实例中,每一个都提供了多集的一个元素和元素的计数。    Set<Multiset.Entry<E>> entrySet()//比较指定对象与此multiset是否相等  boolean equals(Object object)//返回此multiset的HashCodeint hashCode()//返回一个迭代在这个集合中的元素Iterator<E> iterator()//移除此多集multiset的单个出现的指定元素,如果存在boolean remove(Object element)//删除了一些出现,从该多集multiset的指定元素int remove(Object element, int occurrences)//删除所有这一切都包含在指定集合(可选操作)在此集合的元素boolean removeAll(Collection<?> c)//保持那些包含在指定collection(可选操作)在此只集合中的元素boolean retainAll(Collection<?> c)//添加或删除,使得该元素达到所期望的计数的元件的必要出现int setCount(E element, int count)//有条件设置元素的计数为一个新值,如在setCount(对象,INT)中所述,条件是该元素预期的当前计数boolean setCount(E element, int oldCount, int newCount)//返回该对象的字符串表示String toString()

测试

package guavaDome;import java.util.Iterator;import java.util.Set;import com.google.common.collect.HashMultiset;import com.google.common.collect.Multiset;public class MultisetDome {     public static void main(String args[]){          //create a multiset collection          Multiset<String> multiset = HashMultiset.create();          multiset.add("a");          multiset.add("b");          multiset.add("c");          multiset.add("d");          multiset.add("a");          multiset.add("b");          multiset.add("c");          multiset.add("b");          multiset.add("b");          multiset.add("b");          //print the occurrence of an element           System.out.println("Occurrence of 'b' : "+multiset.count("b"));          //print the total size of the multiset           System.out.println("Total Size : "+multiset.size());          //get the distinct elements of the multiset as set          Set<String> set = multiset.elementSet();          //display the elements of the set          System.out.println("Set [");          for (String s : set) {                         System.out.println(s);                   }          System.out.println("]");          //display all the elements of the multiset using iterator          Iterator<String> iterator  = multiset.iterator();          System.out.println("MultiSet [");          while(iterator.hasNext()){             System.out.println(iterator.next());          }          System.out.println("]");                //display the distinct elements of the multiset with their occurrence count          System.out.println("MultiSet [");          for (Multiset.Entry<String> entry : multiset.entrySet())          {             System.out.println("Element: "+entry.getElement() +", Occurrence(s): " + entry.getCount());                      }          System.out.println("]");                //remove extra occurrences           multiset.remove("b",2);          //print the occurrence of an element          System.out.println("Occurence of 'b' : "+multiset.count("b"));       }    }
Occurrence of 'b' : 5Total Size : 10Set [abcd]MultiSet [aabbbbbccd]MultiSet [Element: a, Occurrence(s): 2Element: b, Occurrence(s): 5Element: c, Occurrence(s): 2Element: d, Occurrence(s): 1]Occurence of 'b' : 3

Multimap

多重映射接口扩展映射,使得其键一次可被映射到多个值

//接口声明@GwtCompatiblepublic interface Multimap<K,V>

几个好用得方法

//返回此multimap中的视图,从每个不同的键在键的关联值的非空集合映射。Map<K,Collection<V>> asMap()//将删除所有multimap中的键值对,留下空。void clear()//返回true如果此多重映射包含至少一个键 - 值对用键键和值value。boolean containsEntry(Object key, Object value)//返回true,如果这个multimap中至少包含一个键值对的键keyboolean containsKey(Object key)//返回true,如果这个multimap至少包含一个键值对的值值boolean containsValue(Object value)//返回包含在此multimap中,为Map.Entry的情况下,所有的键 - 值对的视图集合 Collection<Map.Entry<K,V>> entries()//比较指定对象与此多重映射是否相等。boolean equals(Object obj)//返回,如果有的话,在这个multimap中键关联的值的视图集合(返回得key由一个集合来接收)Collection<V> get(K key)//返回此多重映射的哈希码int hashCode()//返回true,如果这个multimap中未包含键 - 值对boolean isEmpty()//返回一个视图集合包含从每个键值对这个multimap中的关键,没有折叠重复Multiset<K> keys()//返回一个视图集都包含在这个映射不同的键   Set<K> keySet()//存储键 - 值对在这个multimap中boolean put(K key, V value)//存储一个键 - 值对在此multimap中的每个值,都使用相同的键 keyboolean putAll(K key, Iterable<? extends V> values)//存储了所有键 - 值对多重映射在这个multimap中,通过返回 boolean putAll(Multimap<? extends K,? extends V> multimap)multimap.entries() 的顺序.//删除一个键 - 值对用键键,并从该多重映射的值的值,如果这样的存在boolean remove(Object key, Object value)//删除与键键关联的所有值   Collection<V> removeAll(Object key)//存储与相同的键值,替换任何现有值的键的集合Collection<V> replaceValues(K key, Iterable<? extends V> values)//返回此多重映射键 - 值对的数量int size()//返回一个视图集合包含从包含在该multimap中的每个键 - 值对的值,而不发生重复 (so values().size() == size())Collection<V> values()

测试

package guavaDome;import java.util.Collection;import java.util.List;import java.util.Map;import java.util.Set;import com.google.common.collect.ArrayListMultimap;import com.google.common.collect.Multimap;public class MultimapDome {    public static void main(String args[]) {        MultimapDome tester = new MultimapDome();        Multimap<String, String> multimap = tester.getMultimap();        List<String> lowerList = (List<String>) multimap.get("lower");        System.out.println("Initial lower case list");        System.out.println(lowerList.toString());        lowerList.add("f");        System.out.println("Modified lower case list");        System.out.println(lowerList.toString());        List<String> upperList = (List<String>) multimap.get("upper");        System.out.println("Initial upper case list");        System.out.println(upperList.toString());        upperList.remove("D");        System.out.println("Modified upper case list");        System.out.println(upperList.toString());        Map<String, Collection<String>> map = multimap.asMap();        System.out.println("Multimap as a map");        for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {            String key = entry.getKey();            Collection<String> value = multimap.get("lower");            System.out.println(key + ":" + value);        }        System.out.println("Keys of Multimap");        Set<String> keys = multimap.keySet();        for (String key : keys) {            System.out.println(key);        }        System.out.println("Values of Multimap");        Collection<String> values = multimap.values();        System.out.println(values);    }    private Multimap<String, String> getMultimap() {        // Map<String, List<String>>        // lower -> a, b, c, d, e        // upper -> A, B, C, D        Multimap<String, String> multimap = ArrayListMultimap.create();        multimap.put("lower", "a");        multimap.put("lower", "b");        multimap.put("lower", "c");        multimap.put("lower", "d");        multimap.put("lower", "e");        multimap.put("upper", "A");        multimap.put("upper", "B");        multimap.put("upper", "C");        multimap.put("upper", "D");        return multimap;    }}

测试结果

Initial lower case list[a, b, c, d, e]Modified lower case list[a, b, c, d, e, f]Initial upper case list[A, B, C, D]Modified upper case list[A, B, C]Multimap as a maplower:[a, b, c, d, e, f]upper:[a, b, c, d, e, f]Keys of MultimaplowerupperValues of Multimap[a, b, c, d, e, f, A, B, C]

BiMap

支持反向操作(位图)

//接口的声明@GwtCompatiblepublic interface BiMap<K,V>extends Map<K,V>

几个常用的方法

//另一种put的形式是默默删除,在put(K, V)运行前的任何现有条目值值V forcePut(K key, V value)//返回此bimap,每一个bimap的值映射到其相关联的键的逆视图BiMap<V,K> inverse()//关联指定值与此映射中(可选操作)指定的键。V put(K key, V value)//将所有从指定映射此映射(可选操作)的映射void putAll(Map<? extends K,? extends V> map)//返回此映射中包含Collection的值视图    Set<V> values()

测试

package guavaDome;import com.google.common.collect.BiMap;import com.google.common.collect.HashBiMap;public class BiMapDome {    public static void main(String args[]) {        BiMap<Integer, String> empIDNameMap = HashBiMap.create();        empIDNameMap.put(new Integer(101), "Mahesh");        empIDNameMap.put(new Integer(102), "Sohan");        empIDNameMap.put(new Integer(103), "Ramesh");        // Emp Id of Employee "Mahesh"        System.out.println(empIDNameMap.inverse().get("Mahesh"));    }}

测试结果

101

Table

在guava库中还提供了一种二维表结构:Table。使用Table可以实现二维矩阵的数据结构
当你想使用多个键做索引的时候guava提供了新集合类型Table,它有两个支持所有类型的键:”行”和”列”

//接口的声明@GwtCompatiblepublic interface Table<R,C,V>

几个好用的方法

//返回集合中的所有行键/列键/值三元组Set<Table.Cell<R,C,V>> cellSet()//从表中删除所有映射void clear()//返回在给定列键的所有映射的视图Map<R,V> column(C columnKey)//返回一组具有表中的一个或多个值的列键Set<C> columnKeySet()//返回关联的每一列键与行键对应的映射值的视图Map<C,Map<R,V>> columnMap()//返回true,如果表中包含与指定的行和列键的映射boolean contains(Object rowKey, Object columnKey)//返回true,如果表中包含与指定列的映射boolean containsColumn(Object columnKey)//返回true,如果表中包含与指定的行键的映射关系boolean containsRow(Object rowKey)//返回true,如果表中包含具有指定值的映射。boolean containsValue(Object value)//比较指定对象与此表是否相等boolean equals(Object obj)//返回对应于给定的行和列键,如果没有这样的映射存在值,返回nullV get(Object rowKey, Object columnKey)//返回此表中的哈希码int hashCode()//返回true,如果表中没有映射。boolean isEmpty()//关联指定值与指定键V put(R rowKey, C columnKey, V value)//复制从指定的表中的所有映射到这个表void putAll(Table<? extends R,? extends C,? extends V> table)//如果有的话,使用给定键相关联删除的映射V remove(Object rowKey, Object columnKey)//返回包含给定行键的所有映射的视图Map<C,V> row(R rowKey)//返回一组行键具有在表中的一个或多个值Set<R> rowKeySet()//返回关联的每一行按键与键列对应的映射值的视图Map<R,Map<C,V>> rowMap()//返回行键/列键/表中的值映射关系的数量int size()//返回所有值,其中可能包含重复的集合Collection<V> values()

测试

package guavaDome;import java.util.Map;import java.util.Set;import com.google.common.collect.HashBasedTable;import com.google.common.collect.Table;public class TableDome {    public static void main(String args[]) {        // Table<R,C,V> == Map<R,Map<C,V>>        /*         * Company: IBM, Microsoft, TCS IBM -> {101:Mahesh, 102:Ramesh,         * 103:Suresh} Microsoft -> {101:Sohan, 102:Mohan, 103:Rohan } TCS ->         * {101:Ram, 102: Shyam, 103: Sunil }         *          */        // create a table        Table<String, String, String> employeeTable = HashBasedTable.create();        // initialize the table with employee details        employeeTable.put("IBM", "101", "Mahesh");        employeeTable.put("IBM", "102", "Ramesh");        employeeTable.put("IBM", "103", "Suresh");        employeeTable.put("Microsoft", "111", "Sohan");        employeeTable.put("Microsoft", "112", "Mohan");        employeeTable.put("Microsoft", "113", "Rohan");        employeeTable.put("TCS", "121", "Ram");        employeeTable.put("TCS", "122", "Shyam");        employeeTable.put("TCS", "123", "Sunil");        // get Map corresponding to IBM        Map<String, String> ibmEmployees = employeeTable.row("IBM");        System.out.println("List of IBM Employees");        for (Map.Entry<String, String> entry : ibmEmployees.entrySet()) {            System.out.println("Emp Id: " + entry.getKey() + ", Name: " + entry.getValue());        }        // get all the unique keys of the table        Set<String> employers = employeeTable.rowKeySet();        System.out.print("Employers: ");        for (String employer : employers) {            System.out.print(employer + " ");        }        System.out.println();        // get a Map corresponding to 102        Map<String, String> EmployerMap = employeeTable.column("102");        for (Map.Entry<String, String> entry : EmployerMap.entrySet()) {            System.out.println("Employer: " + entry.getKey() + ", Name: " + entry.getValue());        }    }}

测试结果

List of IBM EmployeesEmp Id: 103, Name: SureshEmp Id: 101, Name: MaheshEmp Id: 102, Name: RameshEmployers: IBM TCS Microsoft Employer: IBM, Name: Ramesh