背景:
之前在工作中做过这方面的培训,现在和大家分享下培训的内容
Guava是由Google开发的一个Java核心库,它包含了各种Google最佳实践和编程风格的集合。它被设计来填补JDK功能的空白,并提供更简洁的编程接口。Guava广泛应用于企业级和开源项目中,特别是在处理集合、缓存、基础工具类等方面表现出色。
第一部分:Guava的核心特性
集合扩展
Guava提供了对Java集合框架的有效扩展。例如,ImmutableSet
允许开发者创建一个不可变的、性能优化的集合。
ImmutableSet<String> colors = ImmutableSet.of("red", "orange", "yellow");
// 使用不可变集合保证数据安全
缓存
Guava的缓存是一个高性能的本地缓存实现,支持多种缓存过期策略。
LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.removalListener(MY_LISTENER)
.build(
new CacheLoader<Key, Graph>() {
public Graph load(Key key) throws AnyException {
return createExpensiveGraph(key);
}
});
第二部分:Guava与其他工具的对比
Guava vs Apache Commons
- 功能对比:
- Apache Commons和Guava都提供了大量工具类,但Guava通常在集合操作、缓存实现和函数式编程方面更加先进。例如,Guava的集合扩展功能如
Multimap
和BiMap
提供了超出Apache Commons能力的特性。 - 在字符串处理方面,Apache Commons的
StringUtils
类非常强大,但Guava通过Splitter
和Joiner
类提供了更高级和灵活的操作。
- Apache Commons和Guava都提供了大量工具类,但Guava通常在集合操作、缓存实现和函数式编程方面更加先进。例如,Guava的集合扩展功能如
- 性能对比:
- 在性能方面,Guava通常具有更好的优化,特别是在其集合类和缓存实现中。Guava的设计注重高效的内存使用和快速的执行速度。
- 使用Guava的
Multimap
收集键对应多个值的情况。
Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("a", 1);
multimap.put("a", 2);
multimap.put("b", 3);
// 现在可以通过一个键获取多个值
Guava提供的额外特性:
- Java标准库提供了基础的功能,而Guava在此基础上增加了许多高级特性。例如,Guava的
CacheBuilder
可以非常简单地创建自定义缓存,而这在标准库中并不直接可用。 - Guava的函数式编程接口(如
Function
和Predicate
)使得代码更加简洁,尽管Java 8引入了类似的特性,但Guava的这些功能在更早的Java版本中非常有用。
Cache<String, String> cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();
cache.put("key", "value");
String value = cache.getIfPresent("key");
第三部分 Guava 常用工具类
Collections2
- 提供对集合的常用操作,如过滤和转换。
Collection<String> strings = Arrays.asList("one", "two", "three");
Collection<String> filtered = Collections2.filter(strings, Predicates.notNull());
Lists
- 提供对
List
对象的便捷操作,如反转、分区等。
List<String> myList = Lists.newArrayList("one", "two", "three");
List<String> reversed = Lists.reverse(myList);
Sets
- 提供对
Set
对象的扩展操作,如集合交集、并集、差集等。
Set<String> set1 = Sets.newHashSet("one", "two");
Set<String> set2 = Sets.newHashSet("three", "four");
Set<String> union = Sets.union(set1, set2);
Maps
- 提供对
Map
对象的扩展操作,如按值查找、双向映射等。
Map<String, Integer> map = Maps.newHashMap();
map.put("one", 1);
map.put("two", 2);
Integer value = Maps.uniqueIndex(map.entrySet(), Map.Entry::getValue).get(1);
ImmutableList
- 创建不可变的、高效的列表。
ImmutableList<String> immutableList = ImmutableList.of("one", "two", "three");
ImmutableSet
- 创建不可变的、高效的集合。
ImmutableSet<String> immutableSet = ImmutableSet.of("one", "two", "three");
ImmutableMap
- 创建不可变的、高效的映射表。
ImmutableMap<String, Integer> immutableMap = ImmutableMap.of("one", 1, "two", 2);
Multimap
- 支持将多个值映射到一个键的数据结构。
ImmutableMap<String, Integer> immutableMap = ImmutableMap.of("one", 1, "two", 2);
Table
- 支持行和列两个维度的复杂映射结构。
Table<String, String, Integer> table = HashBasedTable.create();
table.put("Row1", "Col1", 1);
BiMap
- 双向映射表,支持键值互换。
BiMap<String, Integer> biMap = HashBiMap.create();
biMap.put("one", 1);
String key = biMap.inverse().get(1);
Cache
- 提供本地缓存实现,支持多种缓存策略。
Cache<String, String> cache = CacheBuilder.newBuilder().maximumSize(1000).build();
cache.put("key", "value");
String value = cache.getIfPresent("key");
LoadingCache
- 自动加载缓存,当缓存未命中时,可以自动加载新值。
LoadingCache<String, String> loadingCache = CacheBuilder.newBuilder()
.build(CacheLoader.from(String::toUpperCase));
String value = loadingCache.getUnchecked("key");
Preconditions
- 用于进行方法参数校验,提高代码的健壮性。
public void setValue(String value) {
Preconditions.checkNotNull(value, "Value cannot be null");
}
Ordering
- 强大的比较器构造工具。
Ordering<String> byLengthOrdering = new Ordering<String>() {
public int compare(String left, String right) {
return Ints.compare(left.length(), right.length());
}
};
Range
- 表示一个范围,如数字或日期间隔。
Range<Integer> range = Range.closed(1, 10);
boolean contains = range.contains(5);
Joiner
- 用于连接对象或字符串,提供多种连接选项。
String result = Joiner.on(", ").skipNulls().join("one", null, "three");
Splitter
- 用于分割字符串,更灵活和强大。
Iterable<String> parts = Splitter.on(',')
.trimResults()
.omitEmptyStrings()
.split("one, ,two, three");
Strings
- 提供对字符串的额外操作,如空字符串处理、前后缀检查等。
String nullToEmpty = Strings.nullToEmpty(null);
boolean isNullOrEmpty = Strings.isNullOrEmpty(nullToEmpty);
MoreObjects
- 辅助创建
Object
方法,如toString
和hashCode
。
@Override
public String toString() {
return MoreObjects.toStringHelper(this).add("key", "value").toString();
}
Throwables
- 对异常的处理和传播提供便利方法。
try {
someMethodThatCouldThrowAnything();
} catch (Throwable t) {
Throwables.propagateIfPossible(t, IOException.class);
throw Throwables.propagate(t);
}