Guava 简介:让 Java 开发更高效

Guava 是由 Google 开源的 Java 库,旨在为开发者提供一系列实用的工具类,以提高开发效率。它包含了集合类、缓存、并发工具、字符串处理等实用方法。

Guava 的常用场景

  1. 集合处理 :Guava 提供了多种扩展的集合类,如 MultisetMultimapTable 等,这些类在处理复杂数据结构时非常有用。

  2. 缓存:Guava 的缓存机制可以帮助开发者轻松实现数据缓存,提高程序性能。

  3. 并发编程 :Guava 提供了强大的并发工具,如 ListenableFuture,使得多线程编程更容易。

  4. 字符串处理 :Guava 提供了方便的字符串工具类,如 JoinerSplitter,用于字符串的拼接和分割。

常用的 API

集合工具类

  • ImmutableList:不可变列表,用于防御性编程和性能提升。

    java 复制代码
    import com.google.common.collect.ImmutableList;
    ImmutableList list = ImmutableList.of("apple", "banana");
  • Multiset:可重复元素的集合。

    java 复制代码
    import com.google.common.collect.HashMultiset;
    HashMultiset multiset = HashMultiset.create();
    multiset.add("apple", 3);
  • Multimap:可重复键的映射。

    java 复制代码
    import com.google.common.collect.ArrayListMultimap;
    ArrayListMultimap multimap = ArrayListMultimap.create();
    multimap.put("fruit", "apple");
    multimap.put("fruit", "banana");
  • BiMap:双向映射,键和值都不能重复。

    java 复制代码
    import com.google.common.collect.HashBiMap;
    HashBiMap bimap = HashBiMap.create();
    bimap.put("key1", "value1");

缓存

  • CacheBuilder :用于构建缓存,支持多种缓存策略。

    java 复制代码
    import com.google.common.cache.CacheBuilder;
    Cache cache = CacheBuilder.newBuilder()
        .maximumSize(1000)
        .expireAfterWrite(10, TimeUnit.MINUTES)
        .build();

并发工具

  • ListenableFuture :支持回调的 Future,用于异步编程。

    java 复制代码
    import com.google.common.util.concurrent.ListenableFuture;
    import com.google.common.util.concurrent.ListeningExecutorService;
    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
    ListenableFuture future = executor.submit(() -> "Hello, World!");
    Futures.addCallback(future, new FutureCallback() {
        @Override
        public void onSuccess(String result) {
            System.out.println(result);
        }
    
        @Override
        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    });

字符串处理

  • Joiner:用于字符串的拼接。

    java 复制代码
    import com.google.common.base.Joiner;
    String joined = Joiner.on(",").join(Arrays.asList("1", "2", "3"));
  • Splitter:用于字符串的分割。

    java 复制代码
    import com.google.common.base.Splitter;
    List parts = Splitter.on(",").splitToList("1,2,3");

其他工具

  • Preconditions:用于参数校验。

    java 复制代码
    import com.google.common.base.Preconditions;
    Preconditions.checkNotNull(obj, "Object cannot be null");
  • Optional:用于处理可能为 null 的值。

    java 复制代码
    import com.google.common.base.Optional;
    Optional optional = Optional.fromNullable("Hello");
    if (optional.isPresent()) {
        System.out.println(optional.get());
    }

解决的问题

  1. 简化代码:Guava 提供了许多实用工具类,帮助开发者简化代码,提高可读性和可维护性。

  2. 提高性能:通过缓存和并发工具,Guava 可以显著提高程序的性能。

  3. 减少错误:Guava 的验证机制和防御性编程方法有助于减少编码错误。

示例:使用 Guava 缓存提高性能

假设我们有一个昂贵的数据库查询操作,我们可以使用 Guava 缓存来缓存查询结果,以提高程序的性能。

java 复制代码
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class DatabaseQueryCache {
    private final LoadingCache cache;

    public DatabaseQueryCache() {
        cache = CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .build(new CacheLoader() {
                    @Override
                    public String load(String key) {
                        // Simulate an expensive database query
                        try {
                            Thread.sleep(1000); // Wait for 1 second
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                        return "Result for " + key;
                    }
                });
    }

    public String query(String key) {
        return cache.getUnchecked(key);
    }

    public static void main(String[] args) {
        DatabaseQueryCache cache = new DatabaseQueryCache();
        System.out.println(cache.query("key1")); // First query takes 1 second
        System.out.println(cache.query("key1")); // Subsequent queries are instant
    }
}

示例:使用 Guava 的 Multimap 处理复杂数据结构

假设我们需要处理一个复杂的数据结构,其中一个键可以对应多个值,我们可以使用 Guava 的 Multimap 来实现。

java 复制代码
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class MultimapExample {
    public static void main(String[] args) {
        Multimap multimap = ArrayListMultimap.create();
        multimap.put("fruit", "apple");
        multimap.put("fruit", "banana");
        multimap.put("vegetable", "carrot");

        System.out.println(multimap.get("fruit")); // Output: [apple, banana]
    }
}

通过这些示例,我们可以看到 Guava 如何帮助我们简化代码、提高性能和减少错误。

相关推荐
星驰云6 分钟前
LLS OAI 项目级会话记录模式 — 为 GitHub Copilot Chat 打造的智能日志助手:一键生成工作日志,告别繁琐汇报
github·copilot
女生也可以敲代码19 分钟前
AI时代下的50道前端开发面试题:从基础到大模型应用
前端·面试
阿丰资源42 分钟前
基于Spring Boot的电影城管理系统(直接运行)
java·spring boot·后端
IT_陈寒44 分钟前
SpringBoot自动配置的坑差点让我加班到天亮
前端·人工智能·后端
消失的旧时光-19432 小时前
Spring Boot 工程化进阶:统一返回 + 全局异常 + AOP 通用工具包
java·spring boot·后端·aop·自定义注解
redreamSo2 小时前
让AI Agent自动接Issue、写代码、上线:我用200行代码搭了一个全自动开发流水线
人工智能·开源·github
Cosolar2 小时前
告别无脑循环:深入解析 ReWOO 与 Plan-and-Execute Agent 架构
人工智能·面试·全栈
追风筝的人er2 小时前
SpringBoot+Vue3 企业考勤如何处理法定假期?节假日方案、调休补班与工作日判断链路拆解
前端·vue.js·后端
Fuly10243 小时前
技术经理面试相关--技术篇
面试·职场和发展
金銀銅鐵3 小时前
[git] 如何丢弃对一个文件的改动?
git·后端