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 }
/* 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 * */
@Test public 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("----------------------------"); //拆分器返回List ArrayList<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 */ @Test public 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 }