Guava常用工具类使用教程

发布于:2025-06-12 ⋅ 阅读:(21) ⋅ 点赞:(0)

概述

  • Google Guava是一个功能强大的Java库,提供了许多实用的工具类。
  • 下面介绍一些最常用的工具类及其使用方法

1. Preconditions - 参数校验工具

Preconditions类提供了一系列静态方法,用于验证方法或构造函数是否被正确调用。

示例代码

import com.google.common.base.Preconditions;

public class PreconditionsExample {
    public static void main(String[] args) {
        // 检查非空
        String name = null;
        // 抛出 NullPointerException: name cannot be null
        // Preconditions.checkNotNull(name, "name cannot be null");
        
        // 检查条件
        int age = -5;
        // 抛出 IllegalArgumentException: Age must be positive
        // Preconditions.checkArgument(age > 0, "Age must be positive");
        
        // 检查索引
        List<String> list = Arrays.asList("a", "b", "c");
        // 抛出 IndexOutOfBoundsException: index (3) must be less than size (3)
        // Preconditions.checkElementIndex(3, list.size(), "index");
    }
}

2. Strings - 字符串工具

Strings类提供了处理字符串的实用方法。

示例代码

import com.google.common.base.Strings;

public class StringsExample {
    public static void main(String[] args) {
        // 检查字符串是否为null或空字符串
        boolean isNullOrEmpty = Strings.isNullOrEmpty("");
        System.out.println("isNullOrEmpty: " + isNullOrEmpty); // true
        
        // 填充字符串
        String padded = Strings.padStart("123", 5, '0');
        System.out.println("Padded: " + padded); // 00123
        
        // 重复字符串
        String repeated = Strings.repeat("abc", 3);
        System.out.println("Repeated: " + repeated); // abcabcabc
        
        // 空字符串转为null
        String emptyToNull = Strings.emptyToNull("");
        System.out.println("Empty to null: " + emptyToNull); // null
    }
}

3. Joiner - 字符串连接工具

Joiner类用于将多个元素连接成一个字符串。

示例代码

import com.google.common.base.Joiner;

public class JoinerExample {
    public static void main(String[] args) {
        // 基本连接
        String joined = Joiner.on(",").join(Arrays.asList(1, 2, 3, 4));
        System.out.println("Joined: " + joined); // 1,2,3,4
        
        // 跳过null值
        String joinedWithSkipNull = Joiner.on(",").skipNulls()
                .join(Arrays.asList("a", null, "b", "c"));
        System.out.println("Joined with skip null: " + joinedWithSkipNull); // a,b,c
        
        // 使用默认值替换null
        String joinedWithDefault = Joiner.on(",").useForNull("unknown")
                .join(Arrays.asList("a", null, "b", "c"));
        System.out.println("Joined with default: " + joinedWithDefault); // a,unknown,b,c
        
        // 连接到StringBuilder
        StringBuilder sb = new StringBuilder();
        Joiner.on(",").appendTo(sb, Arrays.asList(1, 2, 3));
        System.out.println("Appended to StringBuilder: " + sb); // 1,2,3
    }
}

4. Splitter - 字符串分割工具

Splitter类提供了强大的字符串分割功能。

示例代码

import com.google.common.base.Splitter;

public class SplitterExample {
    public static void main(String[] args) {
        // 基本分割
        Iterable<String> split = Splitter.on(",").split("a,b,c,d");
        System.out.println("Split: " + Lists.newArrayList(split)); // [a, b, c, d]
        
        // 去除空白
        Iterable<String> splitTrimmed = Splitter.on(",").trimResults().split(" a , b , c ");
        System.out.println("Split with trim: " + Lists.newArrayList(splitTrimmed)); // [a, b, c]
        
        // 限制分割数量
        Iterable<String> splitLimited = Splitter.on(",").limit(2).split("a,b,c,d");
        System.out.println("Split with limit: " + Lists.newArrayList(splitLimited)); // [a, b,c,d]
        
        // 分割并转换为Map
        Map<String, String> map = Splitter.on(",").withKeyValueSeparator("=")
                .split("key1=value1,key2=value2");
        System.out.println("Split to Map: " + map); // {key1=value1, key2=value2}
    }
}

5. Collections2 - 集合工具

Collections2提供了对集合进行转换和过滤的方法。

示例代码

import com.google.common.collect.Collections2;

public class Collections2Example {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        // 转换集合元素
        Collection<String> strings = Collections2.transform(numbers, Object::toString);
        System.out.println("Transformed: " + strings); // [1, 2, 3, 4, 5]
        
        // 过滤集合元素
        Collection<Integer> evenNumbers = Collections2.filter(numbers, n -> n % 2 == 0);
        System.out.println("Filtered: " + evenNumbers); // [2, 4]
        
        // 获取集合的所有排列
        Collection<List<Integer>> permutations = Collections2.permutations(Arrays.asList(1, 2, 3));
        System.out.println("Permutations: " + permutations);
        // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
    }
}

6. Lists - 列表工具

Lists提供了创建和操作列表的便捷方法。

示例代码

import com.google.common.collect.Lists;

public class ListsExample {
    public static void main(String[] args) {
        // 创建不可变列表
        List<String> immutableList = Lists.newArrayList("a", "b", "c");
        System.out.println("Immutable list: " + immutableList); // [a, b, c]
        
        // 反转列表
        List<String> reversed = Lists.reverse(immutableList);
        System.out.println("Reversed list: " + reversed); // [c, b, a]
        
        // 分块列表
        List<List<Integer>> partitioned = Lists.partition(Arrays.asList(1, 2, 3, 4, 5, 6), 2);
        System.out.println("Partitioned list: " + partitioned); // [[1, 2], [3, 4], [5, 6]]
        
        // 创建ArrayList
        ArrayList<String> arrayList = Lists.newArrayList();
        arrayList.add("item");
        System.out.println("ArrayList: " + arrayList); // [item]
    }
}

7. Maps - 映射工具

Maps提供了创建和操作映射的便捷方法。

示例代码

import com.google.common.collect.Maps;

public class MapsExample {
    public static void main(String[] args) {
        // 创建不可变映射
        Map<String, Integer> immutableMap = Maps.newHashMap();
        immutableMap.put("one", 1);
        immutableMap.put("two", 2);
        System.out.println("Immutable map: " + immutableMap); // {one=1, two=2}
        
        // 创建LinkedHashMap
        LinkedHashMap<String, Integer> linkedMap = Maps.newLinkedHashMap();
        linkedMap.put("one", 1);
        linkedMap.put("two", 2);
        System.out.println("Linked map: " + linkedMap); // {one=1, two=2}
        
        // 创建TreeMap
        TreeMap<String, Integer> treeMap = Maps.newTreeMap();
        treeMap.put("b", 2);
        treeMap.put("a", 1);
        System.out.println("Tree map: " + treeMap); // {a=1, b=2}
        
        // 过滤映射
        Map<String, Integer> filteredMap = Maps.filterValues(immutableMap, value -> value > 1);
        System.out.println("Filtered map: " + filteredMap); // {two=2}
    }
}

8. Cache - 缓存工具

Guava提供了简单易用的内存缓存实现。

示例代码

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.util.concurrent.TimeUnit;

public class CacheExample {
    public static void main(String[] args) {
        // 创建缓存
        Cache<String, String> cache = CacheBuilder.newBuilder()
                .maximumSize(100) // 最大容量
                .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期
                .build();
        
        // 放入缓存
        cache.put("key1", "value1");
        cache.put("key2", "value2");
        
        // 获取缓存
        String value1 = cache.getIfPresent("key1");
        System.out.println("Value1: " + value1); // value1
        
        // 获取缓存,如果不存在则通过Callable加载
        try {
            String value3 = cache.get("key3", () -> {
                // 模拟从数据库或其他数据源加载数据
                System.out.println("Loading value3...");
                return "value3";
            });
            System.out.println("Value3: " + value3); // value3
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        // 移除缓存
        cache.invalidate("key1");
        System.out.println("Value1 after invalidate: " + cache.getIfPresent("key1")); // null
    }
}

9. EventBus - 事件总线

EventBus实现了发布-订阅模式,用于组件间的解耦通信。

示例代码

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

public class EventBusExample {
    // 定义事件类
    static class MessageEvent {
        private final String message;
        
        public MessageEvent(String message) {
            this.message = message;
        }
        
        public String getMessage() {
            return message;
        }
    }
    
    // 定义订阅者
    static class MessageSubscriber {
        @Subscribe
        public void handleMessage(MessageEvent event) {
            System.out.println("Received message: " + event.getMessage());
        }
    }
    
    public static void main(String[] args) {
        // 创建事件总线
        EventBus eventBus = new EventBus();
        
        // 注册订阅者
        MessageSubscriber subscriber = new MessageSubscriber();
        eventBus.register(subscriber);
        
        // 发布事件
        eventBus.post(new MessageEvent("Hello, EventBus!"));
        
        // 取消注册
        eventBus.unregister(subscriber);
        
        // 再次发布事件(订阅者已取消注册,不会收到消息)
        eventBus.post(new MessageEvent("This message will not be received."));
    }
}

10. RateLimiter - 限流工具

RateLimiter用于控制请求的速率,防止系统过载。

示例代码

import com.google.common.util.concurrent.RateLimiter;

import java.util.concurrent.TimeUnit;

public class RateLimiterExample {
    public static void main(String[] args) {
        // 创建每秒允许2个请求的限流器
        RateLimiter rateLimiter = RateLimiter.create(2.0); // 2 permits per second
        
        // 模拟10个请求
        for (int i = 0; i < 10; i++) {
            // 获取令牌,会阻塞直到获取到令牌
            double waitTime = rateLimiter.acquire();
            System.out.println("Request " + i + " executed, waited " + waitTime + " seconds");
            
            // 模拟处理请求
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        // 创建预热限流器(开始时速率较低,逐渐增加到最大值)
        RateLimiter warmUpLimiter = RateLimiter.create(2.0, 3, TimeUnit.SECONDS);
        System.out.println("Warm-up limiter acquired: " + warmUpLimiter.acquire());
    }
}

以上是Guava库中一些最常用的工具类及其使用方法。通过使用这些工具类,可以显著提高Java代码的简洁性、可读性和健壮性。