Featured image of post Guava使用

Guava使用

依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.2.1-jre</version>
</dependency>

Java代码耗时,计算代码执行时长

1
2
3
Stopwatch stopwatch = Stopwatch.createStarted();

log.info("耗时:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");

Guava-Multiset交集、并集、差集

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Set<String> set = Sets.newHashSet();
Set<Integer> set22 = Sets.newHashSet(1, 2, 3, 4);

// MultiSet: 无序+可重复   count()方法获取单词的次数  增强了可读性+操作简单
Multiset<String> multiset = HashMultiset.create();
multiset.add("apple");
multiset.add("banana", 3);
multiset.count("banana"); // 3
for (Multiset.Entry<String> entry : multiset.entrySet()) {
    System.out.println(entry.getElement() + ": " + entry.getCount());
    // apple: 1
    // banana: 3
}

Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5);
Set<Integer> set2 = Sets.newHashSet(4, 5, 6, 7, 8);
// 交集
Sets.SetView<Integer> intersection = Sets.intersection(set1, set2); // 4 5
// 并集
Sets.SetView<Integer> union = Sets.union(set1, set2); //12345678
// 差集,前者比后者多出的部分
Sets.SetView<Integer> diff1 = Sets.difference(set1, set2); //123
Sets.SetView<Integer> diff2 = Sets.difference(set2, set1); //678

Guava-Multimap、MapDifference map集合相等、差集、交集、并集

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Map<String, String> map = Maps.newHashMap();
Map<String, Integer> mapA = Maps.newHashMap(Map.of("a", 1, "b", 2, "c", 3));
Map<String, Integer> mapB = Maps.newHashMap(Map.of("b", 20, "c", 3, "d", 4));
MapDifference<String, Integer> mapDifference = Maps.difference(mapA, mapB);
// 是否相等 false
mapDifference.areEqual();
// 差集 {b=(2, 20)}
mapDifference.entriesDiffering();
// 仅在左侧 {a=1}
mapDifference.entriesOnlyOnLeft();
// 仅在右侧 {d=4}
mapDifference.entriesOnlyOnRight();
// 交集 {c=3}
mapDifference.entriesInCommon();

// 使用双括号初始化(不推荐,因为这样会创建匿名内部类)
Map<String, Integer> map3 = new HashMap<>() {{
put("key1", 1);
put("key2", 2);
}};

// multiMap
Multimap<Integer, String> multiMap = ArrayListMultimap.create();
multiMap.put(1, "a");
multiMap.put(1, "a");
multiMap.put(1, "c");
multiMap.get(1); // [a, a, c]

Guava-ImmutableList不可变集合

1
2
3
4
5
6
7
// 不可变Collection的创建
//(1)在多线程操作下,是线程安全的
//(2)所有不可变集合会比可变集合更有效的利用资源
//(3)中途不可改变,使用add、remove等方法直接抛异常
ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
ImmutableSet<String> iSet = ImmutableSet.of("a", "a");//排重
ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");

Guava-Table双主键集合

1
2
3
4
5
6
7
8
// 双主键table,根据行和列进行查询,可以查询行得到列map,或者根据列得到行map进行遍历
// Table: 双键的Map Map --> Table --> rowKey+columnKey+value
// 和sql中的联合主键有点像
Table<Integer, String, String> tables = HashBasedTable.create();
tables.put(1, "property", "rj");
tables.put(2, "property", "kk");
tables.put(2, "value", "airline");
tables.get(2, "value"); // airline

Guava-BiMap双向map

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// BiMap: 双向Map(Bidirectional Map) 键与值都不能重复
BiMap<String, String> biMap = HashBiMap.create();
biMap.put("key1", "value1");
biMap.put("key2", "value2");
biMap.put("key3", "value2");
biMap.get("key1"); // value1
for (BiMap.Entry<String, String> entry : biMap.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
    // key1 -> value1
    // key2 -> value2
}

Guava-Maps.transformValues-map过滤

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
//自定义过滤条件   使用自定义回调方法对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, input -> {
    if (input > 12) {
        return input;
    } else {
        return input + 1;
    }
});
        
System.out.println(m2);
//{begin=13, code=15}

Guava-LoadingCache实现内存缓存

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/**
 * 缓存 CacheLoader
 */
LoadingCache<String, String> cacheBuilder = CacheBuilder
        .newBuilder()
        .build(new CacheLoader<>() {
            @NotNull
            @Override
            public String load(@NotNull String key) {
                return "hello " + key + "!";
            }
        });
System.out.println(cacheBuilder.getUnchecked("begincode"));  //hello begincode!
System.out.println(cacheBuilder.get("begincode")); //hello begincode!
System.out.println(cacheBuilder.get("wen")); //hello wen!
System.out.println(cacheBuilder.getUnchecked("wen")); //hello wen!
System.out.println(cacheBuilder.getUnchecked("da"));//hello da!
cacheBuilder.put("begin", "code");
System.out.println(cacheBuilder.get("begin")); //code
Licensed under CC BY-NC-SA 4.0
皖ICP备2024056275号-1
发表了80篇文章 · 总计150.57k字
本站已稳定运行