Google Guava使用总结

Google Guava是一个针对Java集合框架的扩展库,旨在提高开发效率。本文涵盖了Guava的初始化集合、使用Multiset统计元素出现次数、MultiMap功能、创建集合及便捷的字符串连接方法。通过这些内容,开发者可以更方便地处理数据和提高代码质量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Guava

Guava简介

Java类库中有不少难用的典型,Collection一定是其中之一。Google最早提出Guava库,是对Java Collection进行扩展以提高开发效率。

Guava依赖引入:

 <dependency>
     <groupId>com.google.guava</groupId>
     <artifactId>guava</artifactId>
     <version>20.0</version>
 </dependency>

初始化集合

//JDK
List<String> list = new ArrayList<String>(); 
list.add("a");
list.add("b");
list.add("c");
list.add("d");

//Guava
List<String> list = Lists.newArrayList("a", "b", "c", "d");

读取文件内容Multiset—类似HashSet

//JDK写法冗长,可以自行搜索

//Guava
List<String> lines =
### Google Guava使用教程与示例代码 Google Guava 是一个功能强大的 Java 工具库,提供了许多简化开发的实用工具和方法。以下将详细介绍其核心功能以及相关的示例代码。 #### 1. Guava Cache 使用示例 Guava 提供了本地缓存的支持,可以通过 `CacheBuilder` 来构建缓存实例[^2]。下面是一个简单的缓存示例: ```java import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.concurrent.TimeUnit; public class GuavaCacheExample { public static void main(String[] args) { // 创建缓存实例,设置缓存过期时间为10秒 Cache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) // 最大缓存条目数为100 .expireAfterWrite(10, TimeUnit.SECONDS) // 缓存写入后10秒过期 .build(); // 添加缓存条目 cache.put("key1", "value1"); // 获取缓存条目 System.out.println("缓存中的值:" + cache.getIfPresent("key1")); // 输出 value1 try { Thread.sleep(11000); // 等待11秒 } catch (InterruptedException e) { e.printStackTrace(); } // 再次获取缓存条目,由于已过期,返回 null System.out.println("缓存中的值:" + cache.getIfPresent("key1")); // 输出 null } } ``` #### 2. Optional 的使用 Guava 提供了 `Optional` 类型来避免空指针异常。以下是使用 `Optional` 的示例代码: ```java import com.google.common.base.Optional; public class GuavaOptionalExample { public static void main(String[] args) { Optional<String> optional = Optional.of("Hello Guava"); if (optional.isPresent()) { System.out.println("Optional 值存在:" + optional.get()); // 输出 Hello Guava } else { System.out.println("Optional 值不存在"); } } } ``` #### 3. Lists 和 Sets 工具类 Guava 提供了许多集合操作的工具类,例如 `Lists` 和 `Sets`,可以方便地进行集合操作[^3]。以下是一个集合过滤的示例: ```java import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class GuavaCollectionsExample { public static void main(String[] args) { List<String> list = Arrays.asList("1", "", "2", "3", null); // 过滤掉空字符串和 null 值 List<String> filteredList = list.stream() .filter(x -> StringUtils.isNotEmpty(x)) .collect(Collectors.toList()); // 将列表转换为逗号分隔的字符串 String result = Lists.newArrayList(filteredList).stream() .collect(Collectors.joining(",")); System.out.println("过滤后的结果:" + result); // 输出 1,2,3 } } ``` #### 4. Retryer 示例 Guava 提供了 `Retryer` 类用于实现重试机制。以下是一个简单的重试示例[^1]: ```java import com.google.common.util.concurrent.Retryer; import com.google.common.util.concurrent.RetryerBuilder; import com.google.common.util.concurrent.SimpleTimeLimiter; import com.google.common.util.concurrent.UncheckedTimeoutException; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class GuavaRetryerExample { public static void main(String[] args) throws Exception { // 构建 Retryer 实例 Retryer<String> retryer = RetryerBuilder.<String>newBuilder() .retryIfResult(result -> "failure".equals(result)) // 如果结果为 failure 则重试 .retryIfException() // 如果抛出异常则重试 .withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) // 每次重试等待1秒 .withStopStrategy(StopStrategies.stopAfterAttempt(3)) // 最多重试3次 .build(); try { String result = retryer.call(() -> { System.out.println("尝试执行任务..."); return "success"; // 返回 success 表示任务成功 }); System.out.println("任务执行结果:" + result); } catch (ExecutionException | UncheckedTimeoutException e) { e.printStackTrace(); } } } ``` ### 总结 Google Guava 库提供了丰富的工具类和方法,能够显著提升开发效率。上述示例展示了缓存、Optional、集合工具类以及重试机制的使用方法。开发者可以根据具体需求选择合适的工具类进行集成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值