Home >Java >javaTutorial >What are the tips for using Java Guava?
Guava is an open source library released by Google. It mainly provides some very useful tool classes and APIs in Java development, such as string processing, set operations, functional programming, caching, etc. wait.
Strings is a set of string tools provided by Guava, which provides many useful methods to process strings. The following are the main methods of Strings:
isNullOrEmpty(String string)
: Determine whether the string is empty or null.
padEnd(String string, int minLength, char padChar)
: Pad the specified characters at the end of the string until the string reaches the specified length.
padStart(String string, int minLength, char padChar)
: Pad the specified characters at the beginning of the string until the string reaches the specified length.
repeat(String string, int count)
: Repeat the specified string a specified number of times.
commonPrefix(CharSequence a, CharSequence b)
: Get the longest common prefix of two strings.
commonSuffix(CharSequence a, CharSequence b)
: Get the longest common suffix of two strings.
The following are examples of using Strings:
public class StringsDemo { public static void main(String[] args) { // 判断字符串是否为空或null String str1 = null; String str2 = ""; System.out.println(Strings.isNullOrEmpty(str1)); System.out.println(Strings.isNullOrEmpty(str2)); // 在字符串末尾填充指定字符,直到字符串达到指定长度 String str3 = "abc"; String paddedStr1 = Strings.padEnd(str3, 6, '*'); System.out.println(paddedStr1); // 在字符串开头填充指定字符,直到字符串达到指定长度 String str4 = "abc"; String paddedStr2 = Strings.padStart(str4, 6, '*'); System.out.println(paddedStr2); // 重复指定字符串指定次数 String str5 = "abc"; String repeatedStr = Strings.repeat(str5, 3); System.out.println(repeatedStr); // 获取两个字符串的最长公共前缀 String str6 = "abcdefg"; String str7 = "abcdxyz"; String commonPrefix = Strings.commonPrefix(str6, str7); System.out.println(commonPrefix); // 获取两个字符串的最长公共后缀 String str8 = "abcdefg"; String str9 = "xyzdefg"; String commonSuffix = Strings.commonSuffix(str8, str9); System.out.println(commonSuffix); }
Guava provides some very useful collection operation APIs, as follows Display:
1.ImmutableList
Immutable collection is an important feature of Guava, which can ensure that the collection is not modified, thereby avoiding the problem of concurrent access. ImmutabelList is an implementation of immutable List. Here is a sample code:
List<String> list = Lists.newArrayList("a", "b", "c"); ImmutableList<String> immutableList = ImmutableList.copyOf(list);
2.Iterables
The Iterables class provides some useful methods to operate collections, as shown below:
Iterable<String> iterable = Lists.newArrayList("a", "b", "c"); // 判断集合是否为空 boolean isEmpty = Iterables.isEmpty(iterable); // 获取第一个元素,如果集合为空返回null String first = Iterables.getFirst(iterable, null); // 获取最后一个元素,如果集合为空返回null String last = Iterables.getLast(iterable, null); // 获取所有符合条件的元素 Iterable<String> filtered = Iterables.filter(iterable, new Predicate<String>() { @Override public boolean apply(String input) { return input.startsWith("a"); } }); // 转换集合类型 List<String> newList = Lists.newArrayList(Iterables.transform(iterable, new Function<String, String>() { @Override public String apply(String input) { return input + input; } }));
3.Multimaps
Multimaps provides a very useful data structure that allows one key to correspond to multiple values. Here is a sample code:
ListMultimap<Integer, String> map = ArrayListMultimap.create(); map.put(1, "a"); map.put(1, "b"); map.put(2, "c"); List<String> values = map.get(1); // 返回[a, b]
4.Maps
Maps provides some useful methods to operate Map, as shown below:
Map<Integer, String> map = ImmutableMap.of(1, "a", 2, "b", 3, "c"); // 判断Map是否为空 boolean isEmpty = Maps.isEmpty(map); // 获取Map中的所有键 Set<Integer> keys = map.keySet(); // 获取Map中的所有值 Collection<String> values = map.values(); // 获取Map中的所有键值对 Set<Map.Entry<Integer, String>> entries = map.entrySet(); // 根据键获取值,如果不存在则返回null String value = Maps.getIfPresent(map, 1);
Preconditions is a set of precondition checking tools provided by Guava, which Some methods are provided to check whether parameters are as expected. The following are the main methods of Preconditions:
checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs)
: Check whether the parameters meet expectations and throw IllegalArgumentException Exceptions can contain error message templates and placeholders.
checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs)
: Check whether the parameter is null and throw a NullPointerException exception, which can contain an error message template and placeholders.
checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs)
: Check whether the object state meets expectations and throw an IllegalStateException exception, which can contain error information Templates and placeholders.
checkElementIndex(int index, int size, String errorMessageTemplate, Object... errorMessageArgs)
: Check whether the subscript is within the range of the collection and throw IndexOutOfBoundsException Exceptions can contain error message templates and placeholders.
checkPositionIndex(int index, int size, String errorMessageTemplate, Object... errorMessageArgs)
: Check whether the subscript is within the range of the set and can be equal to the set size, and throws an IndexOutOfBoundsException exception, which can contain error message templates and placeholders.
checkPositionIndexes(int start, int end, int size)
: Check whether the start subscript and end subscript are within the range of the collection, and throw an IndexOutOfBoundsException exception .
The following is an example of using Preconditions:
public class PreconditionsDemo { public static void main(String[] args) { // 检查参数是否符合预期,并抛出IllegalArgumentException异常,可以包含错误信息模板和占位符 String str1 = "abc"; Preconditions.checkArgument(str1.length() < 3, "字符串长度必须小于3"); // 检查参数是否为null,并抛出NullPointerException异常,可以包含错误信息模板和占位符 String str2 = null; Preconditions.checkNotNull(str2, "字符串不能为空"); // 检查对象状态是否符合预期,并抛出IllegalStateException异常,可以包含错误信息模板和占位符 boolean flag1 = false; Preconditions.checkState(flag1, "状态不正确"); // 检查下标是否在集合的范围内,并抛出IndexOutOfBoundsException异常,可以包含错误信息模板和占位符 List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 5); Preconditions.checkElementIndex(6, list1.size(), "下标越界"); // 检查下标是否在集合的范围内,可以等于集合的大小,并抛出IndexOutOfBoundsException异常,可以包含错误信息模板和占位符 List<Integer> list2 = Lists.newArrayList(1, 2, 3, 4, 5); Preconditions.checkPositionIndex(5, list2.size(), "下标越界"); // 检查开始下标和结束下标是否在集合的范围内,并抛出IndexOutOfBoundsException异常 List<Integer> list3 = Lists.newArrayList(1, 2, 3, 4, 5); Preconditions.checkPositionIndexes(2, 6, list3.size()); // 可以在错误信息中使用占位符 int value1 = 101; Preconditions.checkArgument(value1 <= 100, "值必须小于等于 %s", 100); // 可以使用Supplier来避免计算开销 int value2 = 101; Preconditions.checkArgument(value2 <= 100, () -> "值必须小于等于 " + 100); }
Cache is a caching tool provided by Guava Class, which can help us cache data in memory and improve program performance. The following are the main methods of Cache:
get(K key, Callabled1336e9e686742fb22c1860557381905 valueLoader): Get the cache value of the specified key. If it is not in the cache, call valueLoader to load the data. and stored in cache.
getIfPresent(Object key): Get the cache value of the specified key. If it is not in the cache, return null.
getAllPresent(Iterable6b3d0130bba23ae47fe2b8e8cddf0195 keys): Get the cache value of the specified keys. If there is no cache value, return null.
put(K key, V value): Store the cache value of the specified key in the cache.
putAll(Map90753ef5ffbd6c8060b28e347ac11071 m): Store the cache value of the specified Map into the cache.
invalidate(Object key): Delete the cache value of the specified key from the cache.
invalidateAll(Iterable6b3d0130bba23ae47fe2b8e8cddf0195 keys): Delete the cache value of the specified keys from the cache.
invalidateAll(): Delete all cached values from the cache.
size(): Get the number of cached values in the cache.
asMap(): Convert cache to Map.
public class CacheDemo { public static void main(String[] args) { Cache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); cache.put("key", "value"); String value = cache.getIfPresent("key"); } }
The above is the detailed content of What are the tips for using Java Guava?. For more information, please follow other related articles on the PHP Chinese website!