Spring.Net

Guava 基础

2023-01-31  本文已影响0人  Tinyspot

1. 基础

1.1 guava的核心库

1.2 依赖

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

2. 集合工具(Collections)

2.1 不可变集合

// 普通Collection的创建
List<String> list = Lists.newArrayList();
Set<String> set = Sets.newHashSet();
Map<String, String> map = Maps.newHashMap();

// 不变Collection的创建
ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> iSet = ImmutableSet.of("a", "b");
ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");

immutable(不可变)对象

2.2 Multimap

@Test
public void test() {
    Multimap<String, String> multimap = ArrayListMultimap.create();
    multimap.put("name", "aaa");
    multimap.put("name", "aaa");
    multimap.put("name", "bbb");
    multimap.put("code", "1001");
    // {code=[1001], name=[aaa, aaa, bbb]}
    System.out.println(multimap);
    System.out.println(multimap.get("name"));
}

2.3 Multiset

@Test
public void test() {
    Multiset<String> multiset = HashMultiset.create();
    multiset.add("aaa");
    multiset.add("aaa");
    multiset.add("bbb");
    System.out.println(multiset.count("aaa"));
}

2.4 BiMap

@Test
public void test() {
    BiMap<String, String> biMap = HashBiMap.create();
    biMap.put("name", "aaa");
    // java.lang.IllegalArgumentException: value already present
    biMap.put("other", "aaa");
}

值重复时会抛异常,
IllegalArgumentException – if the given value is already bound to a different key in this bimap
改为 biMap.forcePut("other", "aaa");

3. 缓存

3.1 缓存分类

3.2 CacheBuilder生成器

@Test
public void test() {
    Cache<String,String> cache = CacheBuilder.newBuilder()
            .maximumSize(1024)
            .expireAfterWrite(60, TimeUnit.SECONDS)
            .weakValues() .build();

    cache.put("greet","Hello Guava Cache");
    System.out.println(cache.getIfPresent("greet"));
}

3.3 缓存清除策略

上一篇下一篇

猜你喜欢

热点阅读