Guava API
1、字符串的處理
字符串的連接&拆分&匹配及常用操作
Joiner&Splitter
1 @Test 2 public void testJoiner() { 3 String[] strs = new String[]{"pan",null,"teng"}; 4 //由于字符串中含有null 因此會拋出異常,需要調用以下方法 5 //Joiner joiner = Joiner.on("-").skipNulls(); //跳過 null 6 Joiner joiner = Joiner.on("-").useForNull("空"); //將null用“空” 替換 7 //joiner.skipNulls(); 這樣調用是不行的,不會改變 joiner,需要將skipNulls 返回值賦給joiner才行 8 String joinStr = joiner.join(strs[0], strs[1], strs[2]); 9 System.out.println("joinStr = " + joinStr); 10 //joiner 還可以連接對象,這種情況下 會調用對象的toString方法,將對象轉換為String 11 } Joiner /* CharMatcher 默認常量實現類:* ANY: 匹配任何字符* ASCII: 匹配是否是ASCII字符* BREAKING_WHITESPACE: 匹配所有可換行的空白字符(不包括非換行空白字符,例如"\u00a0")* DIGIT: 匹配ASCII數字 * INVISIBLE: 匹配所有看不見的字符* JAVA_DIGIT: 匹配UNICODE數字, 使用 Character.isDigit() 實現* JAVA_ISO_CONTROL: 匹配ISO控制字符, 使用 Charater.isISOControl() 實現* JAVA_LETTER: 匹配字母, 使用 Charater.isLetter() 實現* JAVA_LETTER_OR_DIGET: 匹配數字或字母* JAVA_LOWER_CASE: 匹配小寫* JAVA_UPPER_CASE: 匹配大寫* NONE: 不匹配所有字符* SINGLE_WIDTH: 匹配單字寬字符, 如中文字就是雙字寬* WHITESPACE: 匹配所有空白字符* * 常用操作方法:* 修剪[trim]、折疊[collapse]、移除[remove]、保留[retain]* CharMatcher is(char match): 返回匹配指定字符的Matcher* CharMatcher isNot(char match): 返回不匹配指定字符的Matcher* CharMatcher anyOf(CharSequence sequence): 返回匹配sequence中任意字符的Matcher* CharMatcher noneOf(CharSequence sequence): 返回不匹配sequence中任何一個字符的Matcher* CharMatcher inRange(char startInclusive, char endIncludesive): 返回匹配范圍內任意字符的Matcher* CharMatcher forPredicate(Predicate<? super Charater> predicate): 返回使用predicate的apply()判斷匹配的Matcher* CharMatcher negate(): 返回以當前Matcher判斷規則相反的Matcher* CharMatcher and(CharMatcher other): 返回與other匹配條件組合做與來判斷的Matcher* CharMatcher or(CharMatcher other): 返回與other匹配條件組合做或來判斷的Matcher* boolean matchesAnyOf(CharSequence sequence): 只要sequence中有任意字符能匹配Matcher,返回true* boolean matchesAllOf(CharSequence sequence): sequence中所有字符都能匹配Matcher,返回true* boolean matchesNoneOf(CharSequence sequence): sequence中所有字符都不能匹配Matcher,返回true* int indexIn(CharSequence sequence): 返回sequence中匹配到的第一個字符的坐標* int indexIn(CharSequence sequence, int start): 返回從start開始,在sequence中匹配到的第一個字符的坐標* int lastIndexIn(CharSequence sequence): 返回sequence中最后一次匹配到的字符的坐標* int countIn(CharSequence sequence): 返回sequence中匹配到的字符計數* String removeFrom(CharSequence sequence): 刪除sequence中匹配到到的字符并返回* String retainFrom(CharSequence sequence): 保留sequence中匹配到的字符并返回* String replaceFrom(CharSequence sequence, char replacement): 替換sequence中匹配到的字符并返回* String trimFrom(CharSequence sequence): 刪除首尾匹配到的字符并返回* String trimLeadingFrom(CharSequence sequence): 刪除首部匹配到的字符* String trimTrailingFrom(CharSequence sequence): 刪除尾部匹配到的字符* String collapseFrom(CharSequence sequence, char replacement): 將匹配到的組(連續匹配的字符)替換成replacement * String trimAndCollapseFrom(CharSequence sequence, char replacement): 先trim在replace* */ 匹配器及常用方法 @Testpublic void testSplitter(){String str = ",b,c,d,,f,";//JDK會自動丟掉最后一個分隔符 且 中間的無論是什么,都作為一個元素 放到數組中String[] strs = str.split(",");for(String s:strs){System.out.println("JDK-split:" + s + "-");}System.out.println("----------------------------");//Guava 提供了更多的可供選擇的模式Iterable<String> iterable = Splitter.on(",").trimResults() //去除元素中的前導空格和后導空格.omitEmptyStrings() //省略空字符串.limit(3) //限制拆分元素的數量 前 n-1個正常拆分,最后的全部的作為1個元素,共拆出n個元素 .split(str);Iterator<String> iterator = iterable.iterator();while (iterator.hasNext()) {System.out.print(iterator.next() + "-" );System.out.println();}//正則表達式匹配拆分System.out.println("--------------正則表達式--------------");String patternStr = "abc12def34ffg78jip";Iterable<String> iterable2 = Splitter.onPattern("[0-9]").split(patternStr);Iterator<String> iterator2 = iterable2.iterator();while (iterator2.hasNext()) {System.out.print(iterator2.next() + "&" );}System.out.println();System.out.println("----------------------------");//拆分器返回ListArrayList<String> list = Lists.newArrayList(iterable);System.out.println(list.get(0) + "-" + list.get(1));//數字匹配器String matchStr = "ab12c*(3de45你好jio:潘騰jA@#B6%7fC^&";System.out.println("保留數字:" + CharMatcher.DIGIT.retainFrom(matchStr));//保留所有數字System.out.println("去除數字:" + CharMatcher.DIGIT.removeFrom(matchStr));System.out.println("數字替換:" + CharMatcher.DIGIT.replaceFrom(matchStr,"*"));//大寫字母匹配器System.out.println("獲取所有大寫字母:" + CharMatcher.JAVA_UPPER_CASE.retainFrom(matchStr));//單字節匹配器(漢字是雙字節)System.out.println("去除單字節,獲取雙字節:" + CharMatcher.SINGLE_WIDTH.removeFrom(matchStr)); 拆分 + 匹配器示例程序?
2、集合
不可變集合:優點-線程安全,不需要考慮變化,節省空間和時間,效率高
? 注意:不可變集合不允許有null對象
/*** 測試不可變集合* @method: testImmutableSet() -by fjt* @TODO: void*/@Testpublic void testImmutableSet(){List<String> list = new ArrayList<String>(Arrays.asList("black","white","red","blue"));Map<String, String> map = new TreeMap<>();map.put("id", "20111907");map.put("name", "panteng");//創建的三種方式copyOf of Builder方法//ImmutableList<String> finalList = ImmutableList.copyOf(list);ImmutableList<String> finalList = ImmutableList.of("black","white","red","blue");//括號內寫 list變量 會報錯try{//finalList.add("yellow"); //拋出空指針異常//finalList.remove(0); //拋出空指針異常}catch(Exception ex){System.out.println("List 異常信息:" + ex.getMessage());}ImmutableMap<String, String> finalMap = ImmutableMap.copyOf(map);try{System.out.println(finalMap.get("name"));finalMap.put("aa", "abcd"); //報異常}catch(Exception ex){System.out.println("Map 異常信息:" + ex.getMessage());}/** 不可變集合類型* ImmutableCollection* ImmutableList* ImmutableSet* ImmutableSortedSet* ImmutableMap* ImmutableSortedMap* ImmutableMultiset* ImmutableSortedMultiset* ImmutableMultimap* ImmutableListMultimap* ImmutableSetMultimap* ImmutableBiMap* ImmutableClassToInstanceMap* ImmutableTable*/} 不可變集合可重復元素的集合,可以將元素看為key,value為出現次數,用于統計。
1 /** 2 * 1. 可以將MultiSet看成map, 作為計數器,key 為元素,值為計數器 3 * 2. 4 */ 5 @Test 6 public void testMultiSet(){ 7 Multiset<String> multisets = HashMultiset.create(); 8 String[] strArray = new String[]{"one","one","two","three"}; 9 10 //添加元素 11 multisets.addAll(Arrays.asList(strArray)); 12 multisets.add("four"); 13 14 //添加指定個數的元素 15 multisets.add("five", 3); 16 //[two, five x 3, one x 2, three, four] 17 System.out.println("打印multiset:" + multisets); 18 //返回元素總個數 19 System.out.println("元素總個數:" + multisets.size()); 20 21 //遍歷 22 Iterator<String> iterator = multisets.iterator(); 23 //two,five,five,five,one,one,three,four, 24 while(iterator.hasNext()){ 25 System.out.print(iterator.next() + ","); 26 } 27 System.out.println(); 28 Set<Entry<String>> entitySet = multisets.entrySet();//????? 29 System.out.println("???" + entitySet); 30 31 //返回給定元素的個數 32 System.out.println("返回指定元素的重復次數:" + multisets.count("one")); 33 34 //移除某元素的一個 35 multisets.remove("one"); 36 System.out.println("移除后:" + multisets.count("one")); 37 //移除某元素的所有 38 multisets.setCount("one",0); 39 System.out.println("移除one所有后:" + multisets); 40 41 //將不同元素放入一個Set 42 Set<String> uniqueSet = multisets.elementSet(); 43 System.out.println("不同元素放入一個SET:" + uniqueSet); 44 45 //設定一個元素的重復次數 46 multisets.setCount("three", 3); 47 System.out.println("打印multiset:" + multisets); 48 49 } 可重復集合? MultiMap - 一個key可以對應多個值,可以認為是一個key對應一個集合,解決一對多的問題
1 @Test 2 /** 3 * ArrayListMultimap 4 HashMultimap 5 LinkedListMultimap* 6 LinkedHashMultimap** 7 TreeMultimap 8 ImmutableListMultimap 9 ImmutableSetMultimap 10 */ 11 public void testMultiMap(){ 12 Multimap<String, String> mutimap = HashMultimap.create(); 13 mutimap.put("father_a", "son_a1"); 14 mutimap.put("father_a", "son_a2"); 15 mutimap.put("father_a", "son_a3"); 16 17 mutimap.put("father_b", "son_b1"); 18 mutimap.put("father_b", "son_b2"); 19 mutimap.put("father_b", "son_b3"); 20 21 //{father_a=[son_a1, son_a3, son_a2], father_b=[son_b3, son_b2, son_b1]} 22 System.out.println("mutimap = " + mutimap); 23 24 //整體添加 25 ArrayList<String> father_c = new ArrayList<String>(); 26 father_c.add("son_C1"); 27 father_c.add("son_C2"); 28 mutimap.putAll("father_c", father_c); 29 30 //獲取某個key對應的元素 31 Collection<String> father_a = mutimap.get("father_c"); 32 Iterator<String> iterator = father_a.iterator(); 33 while (iterator.hasNext()) { 34 System.out.print(iterator.next() + ","); 35 } 36 System.out.println(); 37 38 //獲取鍵值 39 System.out.println("獲取所有的鍵值:" + mutimap.keySet()); 40 41 // 42 } 一對多? 雙向Map,即可以通過key獲取value? 也可以很容易的通過value獲取key? 實現一對一的關系;需要注意的是,必須保證值是唯一的
1 /** 2 * 實際上是調用反轉方法 獲取到一個新的Map 3 */ 4 @Test 5 public void testBiMap(){ 6 Map<String, String> genMap = new HashMap<String, String>(); 7 genMap.put("one", "1"); 8 genMap.put("two", "2"); 9 genMap.put("three", "3"); 10 BiMap<String, String> twoDirectMap = HashBiMap.create(); 11 twoDirectMap.putAll(genMap); 12 System.out.println("one = " + twoDirectMap.get("one")); 13 System.out.println("1 = " + twoDirectMap.get("1")); 14 15 //獲取反轉Map 16 BiMap<String, String> twoDirectMap_mirror = twoDirectMap.inverse(); 17 System.out.println("one = " + twoDirectMap_mirror.get("one")); 18 System.out.println("1 = " + twoDirectMap_mirror.get("1")); 19 20 } 雙向Map?
轉載于:https://www.cnblogs.com/tengpan-cn/p/5752068.html
總結
- 上一篇: zzlinux运维自动化shell脚本小
- 下一篇: 创业板指数超过主板 真的只差一步之遥