Guava Multimap类 _Guava官方教程 - 极悦

Guava教程

Guava Multimap类

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

接口声明

以下是com.google.common.collect.Multimap<K,V>接口的声明:

@GwtCompatible
public interface Multimap<K,V>

接口方法

Multimap 示例

使用所选择的任何编辑器创建下面的java程序 C:/> Guava

GuavaTester.java

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 GuavaTester {
   public static void main(String args[]){
      GuavaTester tester = new GuavaTester();
      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;		
   }
}

验证结果

使用javac编译器编译如下类

C:\Guava>javac GuavaTester.java

现在运行GuavaTester看到的结果

C:\Guava>java GuavaTester

看到结果

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
upper:[a, b, c, d, e, f]
lower:[a, b, c, d, e, f]
Keys of Multimap
upper
lower
Values of Multimap
[A, B, C, a, b, c, d, e, f]

 

 

 

 

转载自并发编程网-ifeve.com

技术文档推荐

更多>>

视频教程推荐

更多>>