Guava是Google开源的一个Java核心库,它提供了许多对日常开发非常有用的工具类和方法。Guava库可以极大地简化代码编写过程,提高代码的可读性和健壮性。Guava的主要功能包括集合操作、缓存、事件监听器、数学运算、字符串处理等。
集合工具
Guava扩展了Java标准库中的集合框架,提供了一些新的集合类型,如ImmutableList
、Multiset
、Multimap
等。
缓存支持
Guava提供了一个轻量级的缓存实现CacheBuilder
,可以帮助开发者快速实现缓存功能。
函数式编程支持
提供了Function
、Predicate
等接口,支持函数式编程风格。
字符串处理
提供了Strings
类,用于处理空字符串、分割字符串等常见操作。
并发工具
提供了ListenableFuture
等工具类,帮助开发者更方便地处理多线程任务。
数学运算
提供了BigIntegerMath
、DoubleMath
等类,用于处理大数运算和浮点数运算。
如果你使用的是Maven项目,可以在pom.xml
中添加以下依赖:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.1-jre</version>
</dependency>
如果是Gradle项目,可以在build.gradle
中添加:
implementation 'com.google.guava:guava:31.1-jre'
Guava提供了不可变集合(Immutable Collections),可以避免集合被意外修改。例如:
import com.google.common.collect.ImmutableList;
public class GuavaExample {
public static void main(String[] args) {
// 创建一个不可变列表
ImmutableList<String> immutableList = ImmutableList.of("apple", "banana", "orange");
// 尝试修改会抛出异常
// immutableList.add("grape"); // 编译错误
System.out.println(immutableList);
}
}
Guava的CacheBuilder
可以轻松实现缓存功能。例如:
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) throws Exception {
// 创建一个缓存,最大容量为100,超过10秒未访问的条目会被移除
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterWrite(10, TimeUnit.SECONDS)
.build();
// 添加缓存条目
cache.put("key1", "value1");
// 获取缓存条目
String value = cache.getIfPresent("key1");
System.out.println(value); // 输出: value1
// 等待10秒后再次获取,缓存已过期
Thread.sleep(11000);
String expiredValue = cache.getIfPresent("key1");
System.out.println(expiredValue); // 输出: null
}
}
Guava的Strings
类提供了许多便捷的字符串处理方法。例如:
import com.google.common.base.Strings;
public class StringsExample {
public static void main(String[] args) {
String str = null;
// 判断字符串是否为空
if (Strings.isNullOrEmpty(str)) {
System.out.println("字符串为空");
}
// 填充字符串到指定长度
String paddedStr = Strings.padStart("123", 5, '0');
System.out.println(paddedStr); // 输出: 00123
}
}
Guava提供了BigIntegerMath
和DoubleMath
等类,用于处理大数和浮点数运算。例如:
import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;
public class MathExample {
public static void main(String[] args) {
BigInteger bigInt = BigInteger.valueOf(10);
// 计算阶乘
BigInteger factorial = BigIntegerMath.factorial(bigInt.intValue());
System.out.println(factorial); // 输出: 3628800
}
}
Guava库是一个非常强大的工具库,能够帮助开发者简化许多日常开发任务。通过使用Guava提供的集合工具、缓存支持、字符串处理等功能,可以显著提高代码的质量和效率。