浅谈Java库之‌Guava

一、Guava库介绍

Guava是Google开发的一个Java核心库,它包含了新的集合类型(如多集合、双端队列等)、并发库、常用工具类(如缓存、预处理和字符串处理)、I/O和时间库等。Guava库旨在提供简洁、高性能的解决方案来处理Java标准库中未涵盖或处理不够好的问题。

二、Guava的主要功能

1、集合 :提供了一系列扩展的集合类型,如Multiset、BiMap、Table等。

2、缓存:提供了一个强大的缓存机制,可以自动管理缓存的大小和过期时间。

3、并发 :提供了一些并发工具类,如ListeningExecutorService、MoreExecutors等。

4、预处理 :提供了Preconditions、Verify等工具类,用于参数校验。

5、字符串处理 :提供了Strings、CharMatcher等工具类,用于字符串操作。

6、I/O :提供了Files、ByteStreams等工具类,用于文件和字节流操作。

7、时间 :提供了TimeLimiter、 Stopwatch等工具类,用于时间相关的操作。

8、函数式编程 :提供了Function、Predicate等函数式接口的实现。

三、Guava的使用

添加Maven依赖

在项目的pom.xml文件中添加Guava依赖:

bash 复制代码
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version> <!-- 使用最新版本 -->
</dependency>
常用工具类和功能的示例
  • 集合操作:
java 复制代码
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

List<String> list = Lists.newArrayList("a", "b", "c");
Set<String> set = Sets.newHashSet("a", "b", "c");
  • 缓存:
java 复制代码
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

LoadingCache<String, String> cache = CacheBuilder.newBuilder()
    .maximumSize(100)
    .expireAfterWrite(10, TimeUnit.MINUTES)
    .build(CacheLoader.from(key -> compute(key)));

String value = cache.getUnchecked("key");
  • 并发工具:
java 复制代码
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(4));
service.submit(() -> {
    // 执行任务
});
  • 预处理:
java 复制代码
import com.google.common.base.Preconditions;

String name = "Kimi";
Preconditions.checkNotNull(name, "Name cannot be null");
  • 字符串处理:
java 复制代码
import com.google.common.base.Strings;

String str = "  Google ";
boolean isNullOrEmpty = Strings.isNullOrEmpty(str);
  • I/O操作:
java 复制代码
import com.google.common.io.Files;

Files.copy(new File("source.txt"), new File("destination.txt"));
  • 时间操作:
java 复制代码
import com.google.common.base.Stopwatch;

Stopwatch stopwatch = Stopwatch.createStarted();
// 执行一些操作
stopwatch.stop();
System.out.println("Time elapsed: " + stopwatch.elapsed(TimeUnit.SECONDS) + "s");
相关推荐
谢亮_vipxieliang18 天前
ValidX vs Google Guava Preconditions:验证 vs 断言
java·spring boot·后端·spring cloud·hibernate·guava
吴声子夜歌21 天前
Guava——散列
java·guava
吴声子夜歌21 天前
Guava——并发(二)
java·网络·guava
吴声子夜歌21 天前
Guava——事件总线
java·网络·guava
吴声子夜歌21 天前
Guava——并发(一)
java·guava
吴声子夜歌21 天前
Guava——反射
java·开发语言·guava
吴声子夜歌22 天前
Guava——基本工具(二)
windows·python·guava
吴声子夜歌22 天前
Guava——基本工具(一)
windows·guava
吴声子夜歌22 天前
Guava——集合(二)
java·guava
吴声子夜歌22 天前
Guava——缓存
缓存·guava