Guava 简介:让 Java 开发更高效

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

Guava 的常用场景

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

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

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

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

常用的 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 如何帮助我们简化代码、提高性能和减少错误。

相关推荐
苏三说技术13 小时前
SpringBoot4.2正式发布,人麻了!
后端
小飞在努力13 小时前
【实现负载均匀在线判题⑤】MVC 架构搭建与 Model 题目数据模块实现
c语言·开发语言·c++·笔记·后端
费曼学习法13 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端
ShineWinsu13 小时前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog
HarmonSir13 小时前
Octop 架构解析:5 个可以直接抄的 Agent 运行时设计
后端·架构
雨中飘荡的记忆14 小时前
一个人、两个 AI,我做出了一张可以点亮的中国美食地图
人工智能·后端
长不大的杨瑞杰15 小时前
GitHub Copilot Browser Use 实战:让 AI 在浏览器里调试与自动化测试
人工智能·github·copilot·playwright·github copilot·browser use
会编程的吕洞宾15 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
技术小代15 小时前
弹窗里的 RegionName 为什么不生效?把区域作用域和模块化一次讲明白|MVVM框架-Prism-3
后端
大侠Luffy15 小时前
用 EmbeddingGemma 2 做一个本地照片与短视频搜索工具
开源·github·ai编程