集合类
Immutable:不可变类型
public class Immutable {
public static void main(String[] args) {
System.out.println("immutableList:");
List<Integer> list = ImmutableList.of(1,2,3,4);
// list.add(1); error
list.stream().forEach(System.out::println);
System.out.println("immutableSet:");
Set<Integer> set = ImmutableSet.of(1,2,3,4);
// set.add(5); error
set.stream().forEach(System.out::println);
System.out.println("immutabaleMap:");
Map<String,String> map = ImmutableMap.of("k1","v1","k2","v2");
// map.put("k3","v3"); error
for (String key : map.keySet()){
System.out.println(key + " : " + map.get(key));
}
}
}
运行结果:
Multi:可重复类型
public class Multi {
public static void main(String[] args) {
System.out.println("Multimap:");
// Multimap
// Multimap<Integer, Integer> map = ArrayListMultimap.create();
// Multimap<Integer,Integer> map = LinkedListMultimap.create();
// Multimap<Integer,Integer> map = HashMultimap.create();
Multimap<Integer,Integer> map = TreeMultimap.create();
map.put(1,1);
map.put(1,2);
map.put(2,3);
for (Integer key : map.keySet()){
System.out.println(key + " : " + map.get(key));
}
System.out.println("Multiset:");
// Multiset
// Multiset<Integer> set = HashMultiset.create();
// Multiset<Integer> set = LinkedHashMultiset.create();
Multiset<Integer> set = TreeMultiset.create();
set.add(1);
set.add(1);
set.add(2);
set.add(3);
for (Integer e : set.elementSet()){
System.out.println(e + " : " + set.count(e));
}
}
}
运行结果:
BiMap & Table:特殊Map类型
public class BiMapAndTable {
public static void main(String[] args) {
System.out.println("BiMap:");
BiMap<String,Integer> map = HashBiMap.create();
map.put("a",1);
map.inverse().put(2,"aa");
map.inverse().inverse().put("aaa",3);
map.put("aaa",4);
// map.inverse().put(5,"aaa"); error
// 强制覆盖
map.inverse().forcePut(5,"aaa");
for (String key : map.keySet()){
System.out.println(key + " : " + map.get(key));
}
System.out.println("Table:");
Table<String,String,Integer> table = HashBasedTable.create();
table.put("a","b",1);
table.put("a","a",2);
table.put("b","b",3);
table.put("b","a",4);
System.out.println(table.get("a","b"));
System.out.println(table.get("a","a"));
}
}
运行结果:
交集、并集、差集
Map
public class MapTest {
public static void main(String[] args) {
Map<String,Integer> mapA = Maps.newHashMap();
mapA.put("a",1);
mapA.put("b",2);
mapA.put("c",3);
Map<String,Integer> mapB = Maps.newHashMap();
mapB.put("d",4);
mapB.put("a",1);
mapB.put("b",20);
MapDifference differenceMap = Maps.difference(mapA,mapB);
// key相同,value不同
System.out.println(differenceMap.entriesDiffering());
// key相同,value相同
System.out.println(differenceMap.entriesInCommon());
// left: key不相同,value不相同
System.out.println(differenceMap.entriesOnlyOnLeft());
// right: key不相同,value不相同
System.out.println(differenceMap.entriesOnlyOnRight());
}
}
运行结果:
Set
public class SetTest {
public static void main(String[] args) {
Set<Integer> setA = new HashSet<>(Arrays.asList(1,2,3,4,5));
Set<Integer> setB = new HashSet<>(Arrays.asList(4,5,6,7,8));
// union
System.out.println("union:");
Sets.SetView<Integer> union = Sets.union(setA,setB);
for (Integer num : union){
System.out.println(num);
}
// difference
System.out.println("difference:");
System.out.println("left difference:");
Sets.SetView<Integer> leftDifference = Sets.difference(setA,setB);
for (Integer num : leftDifference){
System.out.println(num);
}
System.out.println("right difference:");
Sets.SetView<Integer> rightDifference = Sets.difference(setB,setA);
for (Integer num : rightDifference){
System.out.println(num);
}
// intersection
System.out.println("intersection:");
Sets.SetView<Integer> intersection = Sets.intersection(setA,setB);
for (Integer num : intersection){
System.out.println(num);
}
}
}
运行结果:
字符串相关
拼接字符串:Joiner
public class JoinerTest {
public static void main(String[] args) {
// 使用'-'将字符串两两相连
List<String> list = new ArrayList<>(Arrays.asList("aa","bb","cc"));
String res = Joiner.on('-').join(list);
System.out.println(res);
// 将map中的字符串进行拼接
Map<String,Integer> map = new HashMap<>();
map.put("name",1);
map.put("address",2);
map.put("phone",3);
res = Joiner.on(',').withKeyValueSeparator('=').join(map);
System.out.println(res);
}
}
运行结果:
分割字符串:Splitter
public class SplitterTest {
public static void main(String[] args) {
// 根据'-'将字符串分割
List<String> list = new ArrayList<>();
String s = "1-2-3-4-5";
list = Splitter.on('-').splitToList(s);
System.out.println(list.toString());
// 根据'-'将字符串分割,同时忽略null,忽略空格
String str = " 1 - 2 -3-4 -5 -6 ";
list = Splitter.on('-').omitEmptyStrings().trimResults().splitToList(str);
System.out.println(list.toString());
//toMap 将字符串分割成map类型
String str2 = "0 name=2,address=3,phone=3 9";
Map<String,String> map = new HashMap<>();
map = Splitter.on(',').withKeyValueSeparator('=').split(str2);
for (String key : map.keySet()){
System.out.println(key + " : " + map.get(key));
}
//onPattern 使用lamda表达式进行定制化分割
String str3 = "a. ., b,c, d.. ";
list = Splitter.onPattern("[.|,]").omitEmptyStrings().trimResults().splitToList(str3);
System.out.println(list.toString());
}
}
运行结果:
匹配字符串:CharMatch
public class CharMatchertTest {
public static void main(String[] args) {
// 判断匹配结果
boolean flag = CharMatcher.inRange('a','z').or(CharMatcher.inRange('A','Z')).matches('K');
System.out.println(flag);
// 保留文本
String s = CharMatcher.inRange('a','d').retainFrom("yeudnanasan");
System.out.println(s);
// 删除文本
s = CharMatcher.inRange('a','d').removeFrom("yeudnanasan");
System.out.println(s);
}
}
运行结果:
参数校验
主要使用Preconditions类。
public class PreconditionsTest {
public static void main(String[] args) {
String s = new String();
if (Strings.isNullOrEmpty(s)){
System.out.println("is Null or Empty");
}
// Preconditions.checkArgument(s.length() > 0,"%s is null!",s);
s = "work";
System.out.println(Preconditions.checkNotNull(s));
// 检查索引值是否有效
List<Integer> list = Ints.asList(1,2,3,4);
System.out.println(Preconditions.checkElementIndex(3,4));
// 检查范围是否有效
// 如果成立,return null
Preconditions.checkPositionIndexes(0,4,4);
}
}
运行结果:
缓存
满足以下三点建议使用Guava Cache
- 愿意消耗一些内存空间来提升速度,空间换时间
- 判断某些键会被调用多次
- 缓存中存放的数据不大,不会超出内存空间
构建缓存对象
public class CreateCacheTest {
public static void main(String[] args) {
Cache<String,String> cache = CacheBuilder.newBuilder().build();
cache.put("word","hello world!");
System.out.println(cache.getIfPresent("word"));
}
}
运行结果:
设置最大存储
public class CacheMaxSizeTest {
public static void main(String[] args) {
// 设置了最大存储个数,如果put()超出最大个数,会自动删除记录
Cache<String,String> cache = CacheBuilder.newBuilder().maximumSize(2).build();
cache.put("k1","v1");
cache.put("k2","v2");
cache.put("k3","v3");
System.out.println(cache.getIfPresent("k1"));
System.out.println(cache.getIfPresent("k2"));
System.out.println(cache.getIfPresent("k3"));
}
}
运行结果:
设置过期时间
expireAfterWrite:写入后xx时间被删除
expireAfterAccess:过xx时间没有被访问删除
public class expireTest {
public static void main(String[] args) throws InterruptedException {
// 写入后三秒删除
System.out.println("expireAfterWrite:");
Cache<String,String> cache = CacheBuilder.newBuilder().expireAfterWrite(3, TimeUnit.SECONDS).build();
cache.put("key","value");
int count = 1;
while (count <= 10){
System.out.println("第" + count++ + "次取到key值为:" + cache.getIfPresent("key"));
Thread.sleep(1000);
}
// 三秒未被访问就被删除
System.out.println("expireAfterAccess:");
Cache<String,String> cache1 = CacheBuilder.newBuilder().expireAfterAccess(5,TimeUnit.SECONDS).build();
cache1.put("k1","v1");
count = 1;
while (count <= 10){
Thread.sleep(count * 1000);
System.out.println("睡眠" + count++ + "秒后取到k1的值为:" + cache1.getIfPresent("k1"));
}
}
}
运行结果:
弱引用
public class weakKeysTest {
public static void main(String[] args) {
// 没有强引用指向的时候,会被GC回收
Cache<String,Object> cache = CacheBuilder.newBuilder().weakKeys().build();
Object value = new Object();
cache.put("key",value);
value = new Object(); // 原对象不再有强引用
System.gc();
System.out.println(cache.getIfPresent("key"));
}
}
运行结果:
null
显示清除
invalidate(key) 删除一条记录,传入key;
invalidateAll() 删除缓存中的所有记录;
invalidateAll(list) 删除list中的所有记录,传入list(可以传入迭代器)。
public class deleteTest {
public static void main(String[] args) {
Cache<String,String> cache = CacheBuilder.newBuilder().build();
cache.put("k1","v1");
cache.put("k2","v2");
cache.put("k3","v3");
List<String> list = new ArrayList<>();
list.add("k1");
list.add("k2");
cache.invalidateAll(list);
System.out.println(cache.getIfPresent("k1"));
System.out.println(cache.getIfPresent("k2"));
System.out.println(cache.getIfPresent("k3"));
}
}
运行结果:
移除监听器
public class removalListenerTest {
public static void main(String[] args) {
// 记录被删除后,会触发onRemoval()方法
RemovalListener<String,String> listener = new RemovalListener<String, String>() {
@Override
public void onRemoval(RemovalNotification<String, String> notification) {
System.out.println("[" + notification.getKey() + ":" + notification.getValue() + "] is removed");
}
};
Cache<String,String> cache = CacheBuilder.newBuilder().maximumSize(2).removalListener(listener).build();
cache.put("k1","v1");
cache.put("k2","v2");
cache.put("k3","v3");
cache.put("k4","v4");
}
}
运行结果:
自动加载
public class autoLoadTest {
public static Cache<String,String> cache = CacheBuilder.newBuilder().build();
public static void main(String[] args) {
// 如果key缓存中不存在,会调动call()方法去外存加载到缓存,只会加载一次
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread1");
String value = null;
try {
value = cache.get("key", new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("load1");
Thread.sleep(1000);
return "auto load by Callable";
}
});
System.out.println("thread1 " + value);
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread2");
try {
String value = cache.get("key", new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("load1");
Thread.sleep(1000);
return "auto load by Callable";
}
});
System.out.println("thread2 " + value);
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}).start();
}
}
运行结果:
统计信息
public class recordStatsTest {
public static void main(String[] args) {
// 记录统计信息
Cache<String,String> cache = CacheBuilder.newBuilder().recordStats().build();
cache.put("k1","v1");
cache.put("k2","v2");
cache.put("k3","v3");
cache.put("k4","v4");
cache.getIfPresent("k1");
cache.getIfPresent("k2");
cache.getIfPresent("k3");
cache.getIfPresent("k4");
cache.getIfPresent("k5");
cache.getIfPresent("k6");
System.out.println(cache.stats());
}
}
运行结果:
LoadingCache
public class LoadingCacheTest {
public static void main(String[] args) throws ExecutionException {
// LoadingCache是Cache子接口,如果从LoadingCache中读key记录时,如果记录不存在,LoadingCache可以自动执行加载数据到缓存的操作
CacheLoader<String,String> loader = new CacheLoader<String, String>() {
@Override
public String load(String key) throws Exception {
Thread.sleep(1000);
System.out.println(key + "is Loaded from a cacheLoader!");
return key + "is value";
}
};
LoadingCache<String,String> loadingCache = CacheBuilder.newBuilder().build(loader);
loadingCache.get("k1");
loadingCache.get("k2");
loadingCache.get("k3");
}
}
运行结果: