一、简要概述
工具类就是封装平常用的方法,不需要你重复造轮子,节省开发人员时间,提高工作效率。谷歌作为大公司,当然会从日常的工作中提取中很多高效率的方法出来。所以就诞生了guava!
该工具类库主要有以下优点:
-
高效设计良好的API,被Google的开发者设计,实现和使用;
-
遵循高效的java语法实践;
-
使代码更刻度,简洁,简单;
-
节约时间,资源,提高生产力;
其次,Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:
-
集合 [collections]
-
缓存 [caching]
-
原生类型支持 [primitives support]
-
并发库 [concurrency libraries]
-
通用注解 [common annotations]
-
字符串处理 [string processing]
-
I/O 等等。
二、如何使用
注:下面演示的是基于Maven的工程一些操作:
首先导入Google guava依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
三、常用操作
3.1、创建集合
// 普通Collection的创建
List<String> arrayList = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();
//不变Collection的创建
ImmutableList<String> immutableList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> immutableSet = ImmutableSet.of("e1", "e2");
ImmutableMap<String, String> immutableMap = ImmutableMap.of("k1", "v1", "k2", "v2");
创建不可变集合,先理解什么是immutable(不可变)对象:
-
在多线程操作下,是线程安全的;
-
所有不可变集合会比可变集合更有效的利用资源;
-
中途不可改变;
ImmutableList<String> immutableList = ImmutableList.of("1","2","3","4");
注:上面声明了一个不可变的List集合,List中有数据1,2,3,4。
类中的 操作集合的方法(譬如add, set, sort, replace等)都被声明过期,并且抛出异常。 而没用guava之前是需要声明并且加各种包裹集合才能实现这个功能。
比如:add方法:
/** @deprecated */
@Deprecated
public final void add(int index, E element) {
throw new UnsupportedOperationException();
}
3.2、其他黑科技集合
Multiset<String> multiset = HashMultiset.create(); // 特点:元素无序、可重复
演示:
Multiset<String> multiset = HashMultiset.create();
multiset.add("上海");
multiset.add("杭州");
multiset.add("南京");
multiset.add("银川");
multiset.add("上海");
System.out.println("multiset = " + multiset);
multiset = [上海 x 2, 银川, 杭州, 南京]
Multimap<String, String> multimap = ArrayListMultimap.create(); // 特点:元素的 key可以重复
演示:
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("1", "杭州");
multimap.put("2", "深圳");
multimap.put("3", "广州");
multimap.put("2", "北京");
multimap.put("3", "广州");
System.out.println("multimap = " + multimap);
multimap = {1=[杭州], 2=[深圳, 北京], 3=[广州, 广州]}
BiMap<String, String> biMap = HashBiMap.create(); // 特点:双向Map(Bidirectional Map) 键与值都不能重复
演示:
BiMap<String, String> biMap = HashBiMap.create();
biMap.put("1", "上海");
biMap.put("1", "深圳");
biMap.put("2", "广州");
biMap.put("2", "北京");
biMap.put("3", "成都");
System.out.println("biMap = " + biMap);
biMap = {1=深圳, 2=北京, 3=成都}
Table<String, String, Integer> tables = HashBasedTable.create();
演示:
Table<Integer, Integer, Integer> table = HashBasedTable.<Integer, Integer, Integer>create();
table.put(1, 2, 3);
//允许row和column确定的二维点重复
table.put(1, 6, 3);
//判断row和column确定的二维点是否存在
if (table.contains(1, 2)) {
table.put(1, 4, 4);
table.put(2, 5, 4);
}
System.out.println("table = " + table); // {1={4=4, 2=3, 6=3}, 2={5=4}}
//获取column为5的数据集
Map<Integer, Integer> column = table.column(5);
System.out.println("column = " + column); // {2=4}
//获取rowkey为1的数据集
Map<Integer, Integer> row = table.row(1);
System.out.println("row = " + row); // {4=4, 2=3, 6=3}
//获取rowKey为1,columnKey为2的的结果
Integer value = table.get(1, 2);
System.out.println("value = " + value); // 3
//判断是否包含columnKey的值
System.out.println(table.containsColumn(3)); // false
//判断是否包含rowKey为1的视图
System.out.println(table.containsRow(1)); // true
//判断是否包含值为2的集合
System.out.println(table.containsValue(2)); // false
//将table转换为Map套Map格式
Map<Integer, Map<Integer, Integer>> rowMap = table.rowMap();
System.out.println("rowMap = " + rowMap); // {1={4=4, 2=3, 6=3}, 2={5=4}}
//获取所有的rowKey值的集合
Set<Integer> keySet = table.rowKeySet();
System.out.println("keySet = " + keySet); // [1, 2]
//删除rowKey为1,columnKey为2的元素,返回删除元素的值
Integer res = table.remove(1, 2);
//清空集合
table.clear();
System.out.println(res); // 3
System.out.println(table); // null
3.3、集中常见的操作示例
3.3.1、Map中包含key为String类型,value为List类型
// 之前写法:
Map<String,List<Integer>> hashMap = new HashMap<String,List<Integer>>();
List<Integer> arrayList1 = new ArrayList<Integer>();
arrayList1.add(1);
arrayList1.add(2);
hashMap.put("aa", arrayList1);
System.out.println(hashMap.get("aa"));
// 现在写法:
Multimap<String,Integer> map = ArrayListMultimap.create();
map.put("aa", 1);
map.put("aa", 2);
System.out.println(map.get("aa"));
3.3.2、将集合转换为特定规则的字符串
// 之前写法:
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String str = "";
for(int i=0; i<list.size(); i++){
str = str + "-" +list.get(i);
}
//str 为-aa-bb-cc
// 现在写法
List<String> list = new ArrayList<String>();
list.add("aa");
list.add("bb");
list.add("cc");
String result = Joiner.on("-").join(list);
//result为 aa-bb-cc
3.3.3、将Map集合转化为特定规则的字符串
Map<String, Integer> newHashMap = Maps.newHashMap();
newHashMap.put("xiaoming", 12);
newHashMap.put("xiaohong",13);
String join = Joiner.on(",").withKeyValueSeparator("=").join(newHashMap);
System.out.println("join = " + join);
// join = xiaohong=13,xiaoming=12
3.3.4、将String转化为特定的集合
//之前写法:
List<String> list = new ArrayList<String>();
String a = "1-2-3-4-5-6";
String[] strs = a.split("-");
for(int i=0; i<strs.length; i++){
list.add(strs[i]);
}
// 现在写法
String str = "1-2-3-4-5-6";
List<String> list = Splitter.on("-").splitToList(str);
// list = [1, 2, 3, 4, 5, 6]
如果 str="1-2-3-4- 5- 6 ";
guava还可以使用 omitEmptyStrings().trimResults() 去除空串与空格。
strValue = "1-2-3-4- 5- 6 ";
List<String> list2 = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(strValue);
System.out.println("list2 = " + list2);
// list2 = [1, 2, 3, 4, 5, 6]
3.3.5、将String转化为map
String strValue1 = "1=上海,2=广州";
Map<String,String> stringMap = Splitter.on(",").withKeyValueSeparator("=").split(strValue1);
System.out.println("stringMap = " + stringMap);
// stringMap = {1=上海, 2=广州}
3.3.6、guava支持多个字符的切割,或者特定的正则分割
String inputStr = "aa.dd,,ff,,.";
List<String> list3 = Splitter.onPattern("[.|,]")
.omitEmptyStrings()
.splitToList(inputStr);
System.out.println("list3 = " + list3);
// list3 = [aa, dd, ff]
关于字符串的操作 都是在Splitter这个类上进行的:
// 判断匹配结果
boolean flag = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches('K');
System.out.println("flag = " + flag);
// true
// 保留数字文本
String s1 = CharMatcher.inRange('0', '9').retainFrom("abc 123 efg");
System.out.println("s1 = " + s1);
// s1 = 123
// 删除数字文本
String s2 = CharMatcher.digit().removeFrom("abc 123 efg");
System.out.println("s2 = " + s2);
// s2 = abc efg
String s2_1 = CharMatcher.inRange('0', '9').removeFrom("abc 123 efg"); // abc efg
System.out.println("s2_1 = " + s2_1);
// s2_1 = abc efg
3.3.7、集合的过滤
我们对于集合的过滤,思路就是迭代,然后再具体对每一个数判断,这样的代码放在程序中,难免会显得很臃肿,虽然功能都有,但是很不好看。
下面演示的是guava写法:
//按照条件过滤
ImmutableList<String> names = ImmutableList.of("begin", "code", "Guava", "Java");
Iterable<String> fitered = Iterables.filter(names, Predicates.or(Predicates.equalTo("Guava"), Predicates.equalTo("Java")));
System.out.println("fitered = " + fitered);
//自定义过滤条件 使用自定义回调方法对Map的每个Value进行操作
ImmutableMap<String, Integer> m = ImmutableMap.of("begin", 12, "code", 15);
// Function<F, T> F表示apply()方法input的类型,T表示apply()方法返回类型
Map<String, Integer> m2 = Maps.transformValues(m, new Function<Integer, Integer>() {
public Integer apply(Integer input) {
if (input > 12) {
return input;
} else {
return input + 1;
}
}
});
System.out.println("m2 = " + m2);
// fitered = [Guava, Java]
// m2 = {begin=13, code=15}
3.3.8、set的交集、并集、差集
HashSet setA = Sets.newHashSet(1, 2, 3, 4, 5);
HashSet setB = Sets.newHashSet(4, 5, 6, 7, 8);
Sets.SetView<Integer> union = Sets.union(setA, setB);
System.out.println("union:");
for (Integer integer : union)
System.out.println(integer); //union 并集:12345867
Sets.SetView<Integer> difference = Sets.difference(setA, setB);
System.out.println("difference:");
for (Integer integer : difference)
System.out.println(integer); //difference 差集:123
Sets.SetView<Integer> intersection = Sets.intersection(setA, setB);
System.out.println("intersection:");
for (Integer integer : intersection)
System.out.println(integer); //intersection 交集:45
3.3.9、map的交集、并集、差集
HashMap<String, Integer> mapA = Maps.newHashMap();
mapA.put("a", 1);
mapA.put("b", 2);
mapA.put("c", 3);
HashMap<String, Integer> mapB = Maps.newHashMap();
mapB.put("b", 20);
mapB.put("c", 3);
mapB.put("d", 4);
MapDifference differenceMap = Maps.difference(mapA, mapB);
// 比较两个Map是否有差异
boolean flag1 = differenceMap.areEqual();
System.out.println("flag1 = " + flag1);
// 返回 键相同但是值不同值映射项
Map entriesDiffering = differenceMap.entriesDiffering();
// 返回 键只存在于左边Map的映射项
Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
// 返回 键只存在于右边Map的映射项
Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
// 返回 两个map都有的部分(交集)
Map entriesInCommon = differenceMap.entriesInCommon();
System.out.println(entriesDiffering); // {b=(2, 20)}
System.out.println(entriesOnlyOnLeft); // {a=1}
System.out.println(entriesOnlyOnRight); // {d=4}
System.out.println(entriesInCommon); // {c=3}
3.3.10、检查参数
String s1 = "";
if (!Strings.isNullOrEmpty(str)) {
}
Preconditions.checkArgument(Strings.isNullOrEmpty(str), "参数不能为空: %s", s1);
免去了很多麻烦!并且会使你的代码看上去更好看。而不是代码里面充斥着 !=null, !=""
注:检查是否为空,不仅仅是字符串类型,其他类型的判断,全部都封装在 Preconditions类里,里面的方法全为静态。
其中的一个方法的源码:
@CanIgnoreReturnValue
public static <T> T checkNotNull(T reference) {
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
| 方法声明(不包括额外参数) | 描述 | 检查失败时抛出的异常 |
|---|---|---|
| checkArgument(boolean) | 检查boolean是否为true,用来检查传递给方法的参数。 | IllegalArgumentException |
| checkNotNull(T) | 检查value是否为null,该方法直接返回value,因此可以内嵌使用checkNotNull。 | NullPointerException |
| checkState(boolean) | 用来检查对象的某些状态。 | IllegalStateException |
| checkElementIndex(int index, int size) | 检查index作为索引值对某个列表、字符串或数组是否有效。 index > 0 && index < size | IndexOutOfBoundsException |
| checkPositionIndexes(int start, int end, int size) | 检查[start,end]表示的位置范围对某个列表、字符串或数组是否有效 | IndexOutOfBoundsException |
示例演示:
// 检查boolean是否为true,当值为false时,检查失败抛出 IllegalArgumentException
boolean status = true;
Preconditions.checkArgument(status);
// 检查value是否为null,该方法直接返回value,当值为null时,检查抛出NullPointerException;不为空时,返回当前值
String string = null;
String newString = Preconditions.checkNotNull(string);
System.out.println("newString = " + newString);
// 用来检查对象的某些状态,值为false时,抛出异常IllegalStateException
Preconditions.checkState(true);
3.3.11、MoreObjects
该方法是在Objects过期后官方推荐使用的替代品,该类最大的好处就是不用大量的重写 toString,用一种很优雅的方式实现重写,或者在某个场景定制使用。
User user = new User("001", "xxkfz");
String userStr = MoreObjects.toStringHelper("User")
.add("userName", user.getUserName())
.toString();
System.out.println("userStr = " + userStr);
// userStr = User{userName=xxkfz}
3.3.12、强大的Ordering排序器
排序器[Ordering]是Guava流畅风格比较器[Comparator]的实现,它可以用来为构建复杂的比较器,以完成集合排序的功能。
natural() 对可排序类型做自然排序,如数字按大小,日期按先后排序 usingToString() 按对象的字符串形式做字典排序[lexicographical ordering] from(Comparator) 把给定的Comparator转化为排序器 reverse() 获取语义相反的排序器 nullsFirst() 使用当前排序器,但额外把null值排到最前面。 nullsLast() 使用当前排序器,但额外把null值排到最后面。 compound(Comparator) 合成另一个比较器,以处理当前排序器中的相等情况。 lexicographical() 基于处理类型T的排序器,返回该类型的可迭代对象Iterable<T>的排序器。 onResultOf(Function) 对集合中元素调用Function,再按返回值用当前排序器排序。
User user1 = new User("user1", 14);
User user2 = new User("user2", 13);
Ordering<User> byOrdering = Ordering.natural()
.nullsFirst()
.onResultOf(new Function<User, String>() {
public String apply(User u) {
return u.getAge().toString();
}
});
System.out.println("byOrdering.compare(user1, user2) = " + byOrdering.compare(user1, user2));
// user1 的年龄比user2大 所以输出1
//byOrdering.compare(user1, user2) = 1
3.3.13、计算中间代码的运行时间
Stopwatch stopwatch = Stopwatch.createStarted();
for(int i=0; i<100000; i++){
// do something
}
long nanos = stopwatch.elapsed(TimeUnit.MILLISECONDS);
System.out.println("nanos = " + nanos);
注:TimeUnit 可以指定时间输出精确到多少时间。
3.3.14、guava缓存
guava的缓存设计的比较巧妙,可以很精巧的使用。guava缓存创建分为两种,一种是CacheLoader,另一种则是callback方式。
CacheLoader方式:
LoadingCache<String,String> cahceBuilder=CacheBuilder
.newBuilder()
.build(new CacheLoader<String, String>(){
@Override
public String load(String key) throws Exception {
String strProValue="hello "+key+"!";
return strProValue;
}
});
System.out.println(cahceBuilder.apply("begincode")); //hello begincode!
System.out.println(cahceBuilder.get("begincode")); //hello begincode!
System.out.println(cahceBuilder.get("wen")); //hello wen!
System.out.println(cahceBuilder.apply("wen")); //hello wen!
System.out.println(cahceBuilder.apply("da"));//hello da!
cahceBuilder.put("begin", "code");
System.out.println(cahceBuilder.get("begin")); //code
api中已经把apply声明为过期,声明中推荐使用get方法获取值。
callback方式:
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
String resultVal = cache.get("code", new Callable<String>() {
public String call() {
String strProValue="begin "+"code"+"!";
return strProValue;
}
});
System.out.println("value : " + resultVal);
//value : begin code










