当前位置: 首页 > news >正文

Guava常用工具类使用教程

概述

  • 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// 空字符串转为nullString 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// 使用默认值替换nullString joinedWithDefault = Joiner.on(",").useForNull("unknown").join(Arrays.asList("a", null, "b", "c"));System.out.println("Joined with default: " + joinedWithDefault); // a,unknown,b,c// 连接到StringBuilderStringBuilder 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]// 分割并转换为MapMap<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]]// 创建ArrayListArrayList<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}// 创建LinkedHashMapLinkedHashMap<String, Integer> linkedMap = Maps.newLinkedHashMap();linkedMap.put("one", 1);linkedMap.put("two", 2);System.out.println("Linked map: " + linkedMap); // {one=1, two=2}// 创建TreeMapTreeMap<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 {@Subscribepublic 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代码的简洁性、可读性和健壮性。

相关文章:

  • 《Redis》持久化
  • Oracle线上故障问题解决
  • SpringMVC异步处理Servlet
  • Flask应用中处理异步事件(后台线程+事件循环)的方法
  • 达梦数据库 单机部署dmhs同步复制(DM8—>DM8)
  • 高频面试之6Hive
  • Redis: List类型
  • Redis免费客户端工具推荐
  • Github月度新锐热门工具 - 202506
  • [HarmonyOSNext鸿蒙开发]11.ArkUI框架:Swiper、Grid布局与代码复用实战指南
  • Spring Boot 集成 Redis 实战教程
  • spring boot源码和lib分开打包
  • AWS CloudFormation实战:构建可复用的ECS服务部署模板
  • AWS TAM行为面试模拟题
  • onnx 模型转 rknn 部署 rk3588 开发板
  • Centos与RockLinux设置静态ip
  • TripGenie:畅游济南旅行规划助手:团队工作纪实(十四)
  • 26-Oracle 23 ai Automatic Transaction Rollback(行锁终结者)
  • 如何正确的用Trae 打开 Unity 3D 项目
  • 神经网络全景图:五大核心架构详解与本质区别
  • 怎么让网站排名下降/5000人朋友圈推广多少钱
  • 百度收录网站怎么更改关键词/广东seo网站优化公司
  • 商旅平台app下载/seo优化招商
  • 温州做网站建设多少钱/游戏推广员是诈骗吗
  • 网站开发的选题审批表/安徽搜索引擎优化
  • 内部网站建设教程/百度竞价软件哪个好