Guava学习——集合工具

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

Multiset

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

//接口的声明
@GwtCompatible
public 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的HashCode
int 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' : 5
Total Size : 10
Set [
a
b
c
d
]
MultiSet [
a
a
b
b
b
b
b
c
c
d
]
MultiSet [
Element: a, Occurrence(s): 2
Element: b, Occurrence(s): 5
Element: c, Occurrence(s): 2
Element: d, Occurrence(s): 1
]
Occurence of 'b' : 3

Multimap

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

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

几个好用得方法

//返回此multimap中的视图,从每个不同的键在键的关联值的非空集合映射。Map<K,Collection<V>> asMap()

//将删除所有multimap中的键值对,留下空。void clear()

//返回true如果此多重映射包含至少一个键 - 值对用键键和值value。boolean containsEntry(Object key, Object value)

//返回true,如果这个multimap中至少包含一个键值对的键key
boolean 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中的每个值,都使用相同的键 key
boolean 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 map
lower:[a, b, c, d, e, f]
upper:[a, b, c, d, e, f]
Keys of Multimap
lower
upper
Values of Multimap
[a, b, c, d, e, f, A, B, C]

BiMap

支持反向操作(位图)

//接口的声明
@GwtCompatible
public 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,它有两个支持所有类型的键:”行”和”列”

//接口的声明
@GwtCompatible
public 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)

//返回对应于给定的行和列键,如果没有这样的映射存在值,返回null
V 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 Employees
Emp Id: 103, Name: Suresh
Emp Id: 101, Name: Mahesh
Emp Id: 102, Name: Ramesh
Employers: IBM TCS Microsoft 
Employer: IBM, Name: Ramesh
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值