Guava(石榴)使用研究-Google开源Collection类库

1)Guava 简介

Guava 中文是石榴的意思,该项目是 Google 的一个开源项目,包含许多 Google 核心的 Java 常用库。

目前主要包含:

  • com.google.common.annotations
  • com.google.common.base
  • com.google.common.collect
  • com.google.common.io
  • com.google.common.net
  • com.google.common.primitives
  • com.google.common.util.concurrent

在线API doc:http://www.osctools.net/apidocs/apidoc?api=guava

2)代码实现

package test;

 

import java.text.DecimalFormat;

import java.util.Arrays;

import java.util.Collection;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.concurrent.ConcurrentMap;

import java.util.concurrent.TimeUnit;

 

import com.google.common.base.Function;

import com.google.common.base.Predicate;

import com.google.common.collect.Collections2;

import com.google.common.collect.HashMultimap;

import com.google.common.collect.HashMultiset;

import com.google.common.collect.ImmutableSet;

import com.google.common.collect.Lists;

import com.google.common.collect.MapMaker;

import com.google.common.collect.Ordering;

import com.google.common.collect.ImmutableSet.Builder;

 

/**

 * @author gaozzsoft

 *

 */

public class MyGuavaTest {

 

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

List list = Lists.newArrayList();

 

//1 Immutable Collections: 真正的不可修改的集合

Set<String> set = new HashSet<String>(Arrays.asList(new String[]{"RED", "GREEN"})); 

Set<String> unmodifiableSet = Collections.unmodifiableSet(set); 

 

ImmutableSet<String> immutableSet = ImmutableSet.of("RED", "GREEN"); 

 

ImmutableSet<String> immutableSet2 = ImmutableSet.copyOf(set); 

 

Builder<String>  builder = ImmutableSet.builder(); 

ImmutableSet<String> immutableSet3 = builder.add("RED").addAll(set).build(); 

 

// Multiset: 把重复的元素放入集合

List<String> wordList =Arrays.asList(new String[]{"RED", "GREEN"});

Map<String, Integer> map = new HashMap<String, Integer>(); 

for(String word : wordList){ 

   Integer count = map.get(word); 

   map.put(word, (count == null) ? 1 : count + 1); 

//count word “RED”

Integer count = map.get("RED"); 

 

// Quit good method

HashMultiset<String> multiSet = HashMultiset.create(); 

multiSet.addAll(wordList); 

//count word “RED”

Integer count2 = multiSet.count("RED"); 

 

 

 

//2 Multimap: 在 Map 的 value 里面放多个元素

//Key is candidate name, its value is his voters 

HashMap<String, HashSet<String>> hMap = new HashMap<String, HashSet<String>>(); 

List<Ticket> tickets = Lists.newArrayList();

Ticket ticket1 = new Ticket("xijinping","gaozz");

Ticket ticket2 = new Ticket("xijinping","saiwg");

tickets.add(ticket1);

tickets.add(ticket2);

 

for(Ticket ticket: tickets){ 

   HashSet<String> set2 = hMap.get(ticket.getCandidate()); 

   if(set2 == null){ 

   set2 = new HashSet<String>(); 

       hMap.put(ticket.getCandidate(), set2); 

   } 

   set2.add(ticket.getVoter()); 

}

 

HashMultimap<String, String> map2 = HashMultimap.create(); 

for(Ticket ticket: tickets){ 

   map2.put(ticket.getCandidate(), ticket.getVoter()); 

 

//3 BiMap: 双向 Map

 

// for(Map.Entry<User, Address> entry : map.entreSet()){ 

//    if(entry.getValue().equals(anAddess)){ 

//        return entry.getKey(); 

//    } 

// } 

//     return null; 

 

// return biMap.inverse().get(anAddess); 

// biMap == biMap.inverse().inverse();

 

//4 MapMaker: 超级强大的 Map 构造工具

 

//ConcurrentHashMap with concurrency level 8 

ConcurrentMap<String, Object> map1 = new MapMaker() 

   .concurrencyLevel(8) 

    .makeMap(); 

 

//ConcurrentMap with soft reference key and weak reference value 

ConcurrentMap<String, Object> map3 = new MapMaker() 

   .softKeys() 

   .weakValues() 

   .makeMap(); 

 

//Automatically removed entries from map after 30 seconds since they are created 

ConcurrentMap<String, Object> map4 = new MapMaker()

   .expireAfterWrite(30, TimeUnit.SECONDS) 

   .makeMap();

 

 

//Map size grows close to the 100, the map will evict 

//entries that are less likely to be used again 

ConcurrentMap<String, Object> map5 = new MapMaker()

   .maximumSize(100) 

   .makeMap(); 

 

//Create an Object to the map, when get() is missing in map 

ConcurrentMap<String, Object> map6 = new MapMaker() 

   .makeComputingMap( 

     new Function<String, Object>() { 

       public Object apply(String key) { 

//          return createObject(key); 

       return null;

   }}); 

 

 

//Put all features together!  强大之处

ConcurrentMap<String, Object> mapAll = new MapMaker() 

   .concurrencyLevel(8) 

   .softKeys() 

   .weakValues() 

   .expireAfterWrite(30, TimeUnit.SECONDS) 

   .maximumSize(100) 

   .makeComputingMap( 

     new Function<String, Object>() { 

       public Object apply(String key) { 

//          return createObject(key); 

         return null;

    }}); 

 

//5 元素排序

//假设有个待排序的 List<Foo>,而 Foo 里面有两个排序关键字 int a, int b 和 int c

// Collections.sort(list, new Comparator<Foo>(){    

//    @Override    

//    public int compare(Foo f1, Foo f2) {    

//        int resultA = f1.a – f2.a; 

//        int resultB = f1.b – f2.b; 

//        return  resultA == 0 ? (resultB == 0 ? f1.c – f2.c : resultB) : resultA; 

//}});

 

// Collections.sort(list, new Comparator<Foo>(){    

//    @Override 

//    return ComparisonChain.start()  

//         .compare(f1.a, f2.a)  

//         .compare(f1.b, f2.b) 

//         .compare(f1.c, f2.c).result(); 

//}});

 

// Foo 里面每个排序关键字都已经有了各自的 Comparator,那么利用 ComparisonChain 可以 

// Collections.sort(list, new Comparator<Foo>(){    

//    @Override 

//    return ComparisonChain.start()  

//         .compare(f1.a, f2.a, comparatorA)  

//         .compare(f1.b, f2.b, comparatorB) 

//         .compare(f1.c, f2.c, comparatorC).result(); 

//  }});

 

//Ordring 类还提供了一个组合 Comparator 对象的方法

// 而且 Ordring 本身实现了 Comparator 接口所以它能直接作为 Comparator 使用

// Ordering<Foo> ordering = Ordering.compound(

//     Arrays.asList(comparatorA, comparatorB, comparatorC)); 

// Collections.sort(list, ordering);

 

 

//6 过滤器&&转换器

 

//过滤器

Collection<Integer>  filterCollection = 

       Collections2.filter(list, new Predicate<Integer>(){ 

//    @Override 

   public boolean apply(Integer input) { 

       return input >= 10; 

}}); 

 

//转换器

Set<Integer>  setTmp = null;

Collection<String>  formatCollection = 

     Collections2.transform(setTmp, new Function<Integer, String>(){ 

//    @Override 

   public String apply(Integer input) { 

       return new DecimalFormat("#,###").format(input); 

}} ); 

 

}

}

 

猜你喜欢

转载自gaozzsoft.iteye.com/blog/1779336