Java?Guava的使用技巧整理
Guava簡介
Guava是Google發(fā)布的一個開源庫,主要提供了一些在Java開發(fā)中非常有用的工具類和API,比如字符串處理、集合操作、函數(shù)式編程、緩存等等。不管是工作還是學(xué)習(xí)都是非常值得我們?nèi)ナ煜さ模黄饋砜纯窗伞?/p>
字符串(Strings)
Strings是Guava提供的一組字符串工具,它提供了許多有用的方法來處理字符串。以下是Strings的主要方法:
isNullOrEmpty(String string)
:判斷字符串是否為空或null。padEnd(String string, int minLength, char padChar)
:在字符串末尾填充指定字符,直到字符串達到指定長度。padStart(String string, int minLength, char padChar)
:在字符串開頭填充指定字符,直到字符串達到指定長度。repeat(String string, int count)
:重復(fù)指定字符串指定次數(shù)。commonPrefix(CharSequence a, CharSequence b)
:獲取兩個字符串的最長公共前綴。commonSuffix(CharSequence a, CharSequence b)
:獲取兩個字符串的最長公共后綴。
以下是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); // 重復(fù)指定字符串指定次數(shù) 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); }
集合操作(Collections)
Guava提供了一些非常有用的集合操作API,如下所示:
1.ImmutableList
不可變集合是Guava的一個重要特性,它可以確保集合不被修改,從而避免并發(fā)訪問的問題。ImmutabelList是不可變List的實現(xiàn),下面是一個示例代碼:
List<String> list = Lists.newArrayList("a", "b", "c"); ImmutableList<String> immutableList = ImmutableList.copyOf(list);
2.Iterables
Iterables類提供了一些有用的方法來操作集合,如下所示:
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"); } }); // 轉(zhuǎn)換集合類型 List<String> newList = Lists.newArrayList(Iterables.transform(iterable, new Function<String, String>() { @Override public String apply(String input) { return input + input; } }));
3.Multimaps
Multimaps提供了一個非常有用的數(shù)據(jù)結(jié)構(gòu),它允許一個鍵對應(yīng)多個值,下面是一個示例代碼:
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提供了一些有用的方法來操作Map,如下所示:
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(); // 根據(jù)鍵獲取值,如果不存在則返回null String value = Maps.getIfPresent(map, 1);
條件檢查(Preconditions)
Preconditions是Guava提供的一組前置條件檢查工具,它提供了一些檢查參數(shù)是否符合預(yù)期的方法。以下是Preconditions的主要方法:
checkArgument(boolean expression, String errorMessageTemplate, Object... errorMessageArgs)
:檢查參數(shù)是否符合預(yù)期,并拋出IllegalArgumentException異常,可以包含錯誤信息模板和占位符。checkNotNull(T reference, String errorMessageTemplate, Object... errorMessageArgs)
:檢查參數(shù)是否為null,并拋出NullPointerException異常,可以包含錯誤信息模板和占位符。checkState(boolean expression, String errorMessageTemplate, Object... errorMessageArgs)
:檢查對象狀態(tài)是否符合預(yù)期,并拋出IllegalStateException異常,可以包含錯誤信息模板和占位符。checkElementIndex(int index, int size, String errorMessageTemplate, Object... errorMessageArgs)
:檢查下標是否在集合的范圍內(nèi),并拋出IndexOutOfBoundsException異常,可以包含錯誤信息模板和占位符。checkPositionIndex(int index, int size, String errorMessageTemplate, Object... errorMessageArgs)
:檢查下標是否在集合的范圍內(nèi),可以等于集合的大小,并拋出IndexOutOfBoundsException異常,可以包含錯誤信息模板和占位符。checkPositionIndexes(int start, int end, int size)
:檢查開始下標和結(jié)束下標是否在集合的范圍內(nèi),并拋出IndexOutOfBoundsException異常。
以下是Preconditions的使用示例:
public class PreconditionsDemo { public static void main(String[] args) { // 檢查參數(shù)是否符合預(yù)期,并拋出IllegalArgumentException異常,可以包含錯誤信息模板和占位符 String str1 = "abc"; Preconditions.checkArgument(str1.length() < 3, "字符串長度必須小于3"); // 檢查參數(shù)是否為null,并拋出NullPointerException異常,可以包含錯誤信息模板和占位符 String str2 = null; Preconditions.checkNotNull(str2, "字符串不能為空"); // 檢查對象狀態(tài)是否符合預(yù)期,并拋出IllegalStateException異常,可以包含錯誤信息模板和占位符 boolean flag1 = false; Preconditions.checkState(flag1, "狀態(tài)不正確"); // 檢查下標是否在集合的范圍內(nèi),并拋出IndexOutOfBoundsException異常,可以包含錯誤信息模板和占位符 List<Integer> list1 = Lists.newArrayList(1, 2, 3, 4, 5); Preconditions.checkElementIndex(6, list1.size(), "下標越界"); // 檢查下標是否在集合的范圍內(nèi),可以等于集合的大小,并拋出IndexOutOfBoundsException異常,可以包含錯誤信息模板和占位符 List<Integer> list2 = Lists.newArrayList(1, 2, 3, 4, 5); Preconditions.checkPositionIndex(5, list2.size(), "下標越界"); // 檢查開始下標和結(jié)束下標是否在集合的范圍內(nèi),并拋出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); }
可以設(shè)置過期時間的本地緩存(CacheBuilder)
Cache是Guava提供的一個緩存工具類,它可以幫助我們在內(nèi)存中緩存數(shù)據(jù),提高程序的性能。以下是Cache的主要方法:
- get(K key, Callable<? extends V> valueLoader):獲取指定key的緩存值,如果緩存中沒有,則調(diào)用valueLoader加載數(shù)據(jù)并存入緩存。
- getIfPresent(Object key):獲取指定key的緩存值,如果緩存中沒有,則返回null。
- getAllPresent(Iterable<?> keys):獲取指定keys的緩存值,如果緩存中沒有,則返回null。
- put(K key, V value):將指定key的緩存值存入緩存。
- putAll(Map<? extends K, ? extends V> m):將指定Map的緩存值存入緩存。
- invalidate(Object key):將指定key的緩存值從緩存中刪除。
- invalidateAll(Iterable<?> keys):將指定keys的緩存值從緩存中刪除。
- invalidateAll():將所有緩存值從緩存中刪除。
- size():獲取緩存中緩存值的數(shù)量。
- asMap():將緩存轉(zhuǎn)換成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"); } }
以上是Guava的主要工具類介紹及其使用場景,當然不止這些了,Guava還有Throwables(異常工具類),EventBus(事件總線)等等,它們可以大大提高我們程序的開發(fā)效率,同時也為我們提供了很多方便的工具方法。
到此這篇關(guān)于Java Guava的使用技巧整理的文章就介紹到這了,更多相關(guān)Java Guava內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中數(shù)組和List的互相轉(zhuǎn)換問題小結(jié)
這篇文章主要介紹了Java中數(shù)組和List的互相轉(zhuǎn)換問題小結(jié),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2024-03-03Spring+Quartz配置定時任務(wù)實現(xiàn)代碼
這篇文章主要介紹了Spring+Quartz配置定時任務(wù)實現(xiàn)代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-04-04java 反射 動態(tài)調(diào)用不同類的靜態(tài)方法(推薦)
下面小編就為大家?guī)硪黄狫AVA 反射 動態(tài)調(diào)用不同類的靜態(tài)方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08