Guava是google公司开发的一款Java类库扩展工具包
文档
- https://github.com/google/guava
- https://github.com/google/guava/wiki
- https://guava.dev/releases/snapshot-jre/api/docs/
- https://mvnrepository.com/artifact/com.google.guava/guava
maven 依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
(目录)
示例1:连接字符串
package com.example;
import com.google.common.base.Joiner;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
// JDK 1.8
String var1 = String.join("-", Arrays.asList("A", null, "C", "D"));
System.out.println(var1);
// A-null-C-D
// guava
Joiner joiner = Joiner.on("-").skipNulls();
String var2 = joiner.join("A", null, "C", "D");
System.out.println(var2);
// A-C-D
}
}
示例2:统计元素出现次数
package com.example;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.util.Arrays;
public class Demo {
public static void main(String[] args) {
String[] words = {"A", "B", "C", "B"};
// JDK 1.8
Map<String, Integer> counts = new HashMap<String, Integer>();
for (String word : words) {
Integer count = counts.get(word);
if (count == null) {
counts.put(word, 1);
} else {
counts.put(word, count + 1);
}
}
System.out.println(counts);
// {A=1, B=2, C=1}
// guava
Multiset<String> multiset = HashMultiset.create();
multiset.addAll(Arrays.asList(words));
System.out.println(multiset);
// [A, B x 2, C]
System.out.println(multiset.count("B"));
// 2
}
}
示例3:key对应集合
package com.example;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class Demo {
public static void main(String[] args) {
Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("A", 1);
multimap.put("A", 2);
multimap.put("B", 4);
multimap.put("C", 5);
System.out.println(multimap);
// {A=[1, 2], B=[4], C=[5]}
}
}