摘抄:工具类与特定集合接口的对应关系归纳如下:
-
- 创建集合类
在JDK 7之前,创建集合类时,要声明泛型:
List list = new ArrayList();
guava中,简化为:
List<String> list = Lists.newArrayList();
Map <String, String> map = Maps.newLinkedHashMap();
但Guava的静态工厂方法远不止这么简单。用工厂方法模式,我们可以方便地在初始化时就指定起始元素。
Set<Type> set= Sets.newHashSet(elements);
List<String> list= Lists.newArrayList(“java”, “php”, “.net”)
-
- Lists
List countUp = Ints.asList(1, 2, 3, 4, 5);
List countDown = Lists.reverse(theList); // {5, 4, 3, 2, 1}
List parts = Lists.partition(countUp, 2);//{{1,2}, {3,4}, {5}}
partition(List, int) : 把List按指定大小分割
reverse(List) :返回给定List的反转视图。注: 如果List是不可变的,考虑改用ImmutableList.reverse()。
- 3.Sets
使用范例:
Set wordsWithPrimeLength = ImmutableSet.of(“one”, “two”, “three”, “six”, “seven”, “eight”);
Set primes = ImmutableSet.of(“two”, “three”, “five”, “seven”);
SetView intersection = Sets.intersection(primes,wordsWithPrimeLength);
// intersection包含”two”, “three”, “seven”
return intersection.immutableCopy();//可以使用交集,但不可变拷贝的读取效率更高