诚然,在Java世界中,用的非常广泛的数据结构乃集合也,由Collection及Map衍合而来的多功能结构的集合类和接口,让我们随行随用。然而,工欲善其事,必先利其器,个人的工具箱中,必然应该收藏很多集合工具利器。
此类包含了许多特有的静态方法,用于操作集合或返回集合实例,同时还提供许多处理集合和包装器的多态实现,用于获取一些拥有特定功能的集合。
如果传入给此类任一方法的参数为null,则该方法会抛出NullPointerException。
通常,涉及到的多态实现都有简要的文档描述,这些文档应该是一种注意事项,而不是一种规范,在满足多态规范的前提下,这些实现可由其他算法自由替换。(例如,所使用的算法不需要归并排序,但它必须是稳定的)
此类还包含有”破坏性”的集合实现算法,如果集合不支持相应的突变原语(mutation primitives),那么当修改集合时,该算法会抛出UnsupportedOperationException异常,例如set方法。如果调用对集合没有影响,该算法可能会抛该异常,但不是必须的。例如,对一个有序的不可变集合调用sort方法时,此时可能会抛UnsupportedOperationException但也可能不会。
1.排序方法与排序器
默认为比较器,正序排序
public static <T extends Comparable<? super T>>
void sort(List<T> list)
传入自定义比较器
public static <T> void sort(List<T> list, Comparator<? super T> c)
逆序排序
static void reverse(List<?> list)
逆序排序器
public static <T> Comparator<T> reverseOrder()
public static <T> Comparator<T> reverseOrder(Comparator<T> cmp)
2.随机排列方法
public static void shuffle(List<?> list)
public static void shuffle(List<?> list, Random rnd)
3.交换元素
public static void swap(List<?> list, int i, int j)
4.填充值与拷贝集合
用obj全部填充到list中
public static <T> void fill(List<? super T> list, T obj)
public static <T> void copy(List<? super T> dest, List<? extends T> src)
赋值N个
public static <T> List<T> nCopies(int n, T o)
5.二分查找
默认查找
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
自定义查找规则
public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
6.获取最大最小元素
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)
public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp)
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)
7.集合中索引集合
public static int lastIndexOfSubList(List<?> source, List<?> target)
public static int indexOfSubList(List<?> source, List<?> target)
8.获取不可变集合与同步集合
public static <T> List<T> unmodifiableList(List<? extends T> list)
public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K, ? extends V> m)
public static <T> Set<T> unmodifiableSet(Set<? extends T> s)
public static <T> List<T> synchronizedList(List<T> list)
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m)
9.获取空元素集合与单例集合
public static final <T> Set<T> emptySet()
public static final <T> List<T> emptyList()
public static final <K,V> Map<K,V> emptyMap()
public static <T> Set<T> singleton(T o)
public static <T> List<T> singletonList(T o)
public static <K,V> Map<K,V> singletonMap(K key, V value)
10.其他零散方法
对象比较
static boolean eq(Object o1, Object o2)
o在c中出现的次数
public static int frequency(Collection<?> c, Object o)
添加元素
public static <T> boolean addAll(Collection<? super T> c, T... elements)
大名鼎鼎,Guava也(https://github.com/google/guava)
User Guide: https://github.com/google/guava/wiki
Maven依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
对于任何编程语言,集合皆不可或缺。不用集合,我们几乎无法写出任何有意义的程序,Guava起始于google-collections, 但谷歌早已并之于Guava中,在com.google.common.collect
包一窥便得之。如今,与Guava中其他包相比,集合包中仍有数量繁森的家族成员。囿于此,不能面面俱到的去探索所有繁枝细叶,但我们将倾尽全力去探寻其最深的奥妙处,并应用于日常必须中,我们将对如下内容追本溯源。(此章节翻译自Bill Bejeck – Getting Started with Google Guava)
1.FluentIterable
FluentIterable提供了许多有益的接口,并可以一种流畅的链式风格编写代码,使之可读性良好。
FluentIterable.filter方法
FluentIterable.filter方法采用Predicate
作为参数,如果参入的Predicate
返回true,则每个元素都将被验证并被保留,如果没有元素满足条件,则将返回一个空Iterable。如下例子将演示from
和filler
方法。
@Test
public void testFilter() throws Exception {
Iterable<Person> personsFilteredByAge= FluentIterable.from(personList).filter(new Predicate<Person>() {
@Override
public boolean apply(Person input) {
return input.getAge() > 31;
}
});
assertThat(Iterables.contains(filtered, person2),is(true));
FluentIterable.transform方法
transform方法是一种映射操作,其通过Function
来 应用每一个元素。它可生成一个新的与原始iterable具有同样大小的转换后的iterable,它与filter
方法不同,它不会任意移除元素,如下例子演示一下。
@Test
public void testTransform() throws Exception {
List<String> transformedPersonList =
FluentIterable.from(personList).transform(new Function<Person, String>() {
@Override
public String apply(Person input) {
return Joiner.on('#').join(input.getLastName(),
input.getFirstName(), input.getAge());
}
}).toList();
assertThat(transformed.get(1), is("Flintstone#Fred#32"));
}
2.Lists、Sets、 Maps
Lists、Sets, Maps,是一套工具类,分别用于操作List, Set,Map接口及其实现类,他们最便利的方法是生成相应的实现类实例。
Lists常用方法
创建list系列
public static <E> ArrayList<E> newArrayList()
public static <E> ArrayList<E> newArrayList(E... elements)
public static <E> LinkedList<E> newLinkedList()
public static <E> LinkedList<E> newLinkedList()
public static <E> CopyOnWriteArrayList<E> newCopyOnWriteArrayList()
public static <E> ArrayList<E> newArrayListWithCapacity
转换对象
public static <F, T> List<T> transform( List<F> fromList, Function<? super F, ? extends T> function)
截取子集合返回size个集合
public static <T> List<List<T>> partition(List<T> list, int size)
反转
public static <T> List<T> reverse(List<T> list)
Sets常用方法
public static <E> HashSet<E> newHashSet()
public static <E> HashSet<E> newHashSet(E... elements)
public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize)
public static <E> LinkedHashSet<E> newLinkedHashSet()
并集
public static <E> SetView<E> union( final Set<? extends E> set1, final Set<? extends E> set2)
set1中有set2中没有
public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2)
交集
public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2)
Maps常用方法
public static <K, V> HashMap<K, V> newHashMap()
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap()
public static <K, V> ConcurrentMap<K, V> newConcurrentMap()
public static <K, V1, V2> Map<K, V2> transformValues(
Map<K, V1> fromMap, Function<? super V1, V2> function)
演示Maps.uniqueIndex方法
public static <K, V> ImmutableMap<K, V> uniqueIndex(
Iterable<V> values, Function<? super V, K> keyFunction) List<Book> books = someService.getBooks(); Map<String,Book> bookMap = Maps.uniqueIndex(books.iterator(),new Function<Book, String>(){ @Override public String apply( Book input) { return input.getIsbn(); } });