Guava工具类

原文链接:http://blog.csdn.net/mnmlist/article/details/53425865

 

Objects类

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. Objects类有几个比较不错的方法,toString、hashCode和equals方法  
  2. 测试类  
  3. @Data  
  4. class Person{  
  5.   private String name;  
  6.   private int sex;  
  7.   private int age;  
  8.   
  9.   
  10.   public Person(String name,int sex,int age) {  
  11.     this.name = name;  
  12.     this.sex = sex;  
  13.     this.age = age;  
  14.   }  
  15.   
  16.   
  17.   @Override  
  18.   public String toString() {  
  19.     return MoreObjects.toStringHelper(this)  
  20.             .omitNullValues()  
  21.             .add("name", this.getName())  
  22.             .add("sex", this.getSex())  
  23.             .add("age", this.getAge())  
  24.             .toString();  
  25.   }  
  26. }  
  27.    
  28. 1.重写toString方法,减少if else判空逻辑  
  29. public void testToString() {  
  30.    Person zhangsan = new Person(null, 1, 28);  
  31.    String nameStr = MoreObjects.toStringHelper(zhangsan).omitNullValues()  
  32.          .add("name", zhangsan.getName()).add("sex", zhangsan.getSex())  
  33.          .add("age", zhangsan.getAge()).toString();  
  34.    assetTrue(nameStr.equals("Person{sex=1, age=28}"));  
  35. }  
  36.   
  37.   
  38. 2.获取hash值,null也可以当成数据项  
  39. public void testObjectsHashCode() {  
  40.    int hashCode1 = Objects.hashCode("sting", "tony", null, "vincent");  
  41.    int hashCode2 = Objects.hashCode("sting", "tony", "vincent", null);  
  42.    assertTrue(hashCode1 != hashCode2);  
  43. }  
  44.   
  45.   
  46. 3.比较对象,可以为空,减少判空逻辑  
  47. public void testObjectsEquals() {  
  48.   assertTrue(Objects.equal(null, null));  
  49.   assertTrue(Objects.equal("sting", "sting"));  
  50.   assertTrue(!Objects.equal(null, "test"));  
  51.   //assertTrue(Objects.equal("stings", "sting"));  
  52. }  

排序的实现和改进

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. Person person1 = new Person("zhangsan", 1, 25);  
  2. Person person2 = new Person("lisi", 0, 30);  
  3. Person person3 = new Person(null, 1, 25);  
  4. Person person4 = null;  
  5. List<Person> persons = Lists  
  6.       .newArrayList(person1, person2, person3, person4);  
  7.   
  8. public void testOrderingWithComparisonChain() {  
  9.    assertTrue(persons.toString().equals("[Person{name=zhangsan, sex=1, age=25}, Person{name=lisi, sex=0, age=30}, Person{sex=1, age=25}, null]"));  
  10.    System.out.println(persons.toString());  
  11.    Ordering<Person> personOrdering = new Ordering<Person>() {  
  12.       @Override  
  13.       public int compare(Person p1, Person p2) {  
  14.          return ComparisonChain.start().compare(p1.getAge(), p2.getAge())  
  15.                .compare(p1.getName(), p2.getName())  
  16.                .compare(p1.getSex(), p2.getSex()).result();  
  17.       }  
  18.    }.nullsFirst();  
  19.    Collections.sort(persons, personOrdering);  
  20.    System.out.println(persons.toString());  
  21.    //Collections.sort(persons, personOrdering.reverse());  
  22. }  
  23.   
  24. public void testOrderingWithComparator() {  
  25.    System.out.println(persons.toString());  
  26.    Collections.sort(persons, new Comparator<Person>() {  
  27.       public int compare(Person p1, Person p2) {  
  28.          return ComparisonChain.start().compare(p1.getAge(), p2.getAge())  
  29.                .compare(p1.getName(), p2.getName())  
  30.                .compare(p1.getSex(), p2.getSex()).result();  
  31.       }  
  32.    });  
  33.    System.out.println(persons.toString());  
  34. }  

CharMatcher

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. CharMatcher内部的大量实现  
  2. BREAKING_WHITESPACE:用于匹配所有的可换行的空白符,如 , ,f,   
  3. WHITESPACE:用于匹配所有空白字符  
  4. ASCII:用于匹配ASCII字符  
  5. DIGIT:匹配ASCII数字  
  6. JAVA_DIGIT:匹配unicode数字  
  7. JAVA_LETTER:匹配字母(含中文)  
  8. JAVA_LETTER_OR_DIGIT:匹配字母(含中文)或数字  
  9. JAVA_UPPER_CASE:匹配所有大写字符  
  10. JAVA_LOWER_CASE:匹配所有小写字符  
  11. ANY:用于匹配任意字符  
  12. NONE:不匹配所有字符  
  13.   
  14. CharMatcher提供的工厂方法  
  15. is(final char match):返回匹配指定字符的Matcher  
  16. isNot(final char match):返回不匹配指定字符的Matcher  
  17. anyOf(final CharSequence sequence):返回能够匹配sequence中任一字符的Matcher  
  18. noneOf(CharSequence sequence):返回能够过滤sequence中任一字符的Matcher  
  19. inRange(final char startInclusive, final char endInclusive):返回匹配范围内任意字符的Matcher  
  20. forPredicate(final Predicate<? super Character> predicate):返回使用Predicate的apply()判断匹配的Matcher  
  21. negate():返回与当前Matcher判断规则相反的Matcher  
  22. and(CharMatcher other):返回与other匹配条件组合进行与运算的Matcher  
  23. or(CharMatcher other):返回与other匹配条件组合进行或运算的Matcher  
  24.   
  25. 对匹配字符的操作  
  26. 获取的符合规则的Matcher后,有以下常用方法来处理字符串并返回结果  
  27. removeFrom(CharSequence sequence):去除匹配到的字符  
  28. retainFrom(CharSequence sequence):筛选匹配到的字符  
  29. replaceFrom(CharSequence sequence, char replacement):使用指定字符替换匹配到的字符  
  30. replaceFrom(CharSequence sequence, CharSequence replacement):使用指定字符替换匹配到的字符  
  31. trimFrom(CharSequence sequence):去除首尾匹配到的字符  
  32. trimLeadingFrom(CharSequence sequence):去除首部匹配到的字符  
  33. trimTrailingFrom(CharSequence sequence):去除尾部匹配到的字符  
  34. collapseFrom(CharSequence sequence, char replacement):将匹配到的字符组(多个字符)替换成指定字符  
  35. trimAndCollapseFrom(CharSequence sequence, char replacement):去除首尾空格后进行字符替换  
  36.   
  37. 判定型方法  
  38. matchesAnyOf(CharSequence sequence):如果sequence中任一字符匹配,返回true  
  39. matchesAllOf(CharSequence sequence):如果sequence中所有字符都匹配,返回true  
  40. matchesNoneOf(CharSequence sequence):如果sequence中所有字符都不匹配,返回true  
  41.   
  42. 获取字符索引的方法  
  43. indexIn(CharSequence sequence):返回匹配到的第一个字符的索引  
  44. indexIn(CharSequence sequence, int start):返回从指定索引开始,匹配到的第一个字符的索引  
  45. lastIndexIn(CharSequence sequence):返回匹配到的最后一个字符的索引  
  46. countIn(CharSequence sequence):返回匹配到的字符数量  
  47.    
  48. @Test  
  49. public void testAnyOf() {  
  50.    assertTrue(CharMatcher.anyOf("gZ").matchesAnyOf("anything"));  
  51. }  
  52.   
  53. @Test  
  54. public void testNoneOf() {  
  55.    assertTrue(CharMatcher.noneOf("xZ").matchesAnyOf("anything"));  
  56. }  
  57.   
  58. @Test  
  59. public void testMatchAny() {  
  60.    assertTrue(CharMatcher.ANY.matchesAllOf("anything"));  
  61. }  
  62.   
  63. @Test  
  64. public void testMatchAllOf() {  
  65.    assertTrue(CharMatcher.BREAKING_WHITESPACE.matchesAllOf(" "));  
  66. }  
  67.   
  68. @Test  
  69. public void testMatchDigits() {  
  70.    assertTrue(CharMatcher.JAVA_DIGIT.matchesAllOf("1231212"));  
  71. }  
  72.   
  73. @Test  
  74. public void testRetainFrom() {  
  75.    assertTrue(CharMatcher.DIGIT.retainFrom("Hello 1234 567").equals("1234567"));  
  76. }  
  77.   
  78. @Test  
  79. public void testRetailFrom() {  
  80.    System.out.println(CharMatcher.DIGIT.or(CharMatcher.WHITESPACE).retainFrom("Hel**lo 1234 567"));  
  81.    assertTrue(CharMatcher.DIGIT.or(CharMatcher.WHITESPACE).retainFrom("Hel**lo 1234 567").equals(" 1234 567"));  
  82. }  
  83.   
  84. @Test  
  85. public void testCollapseFrom() {  
  86.    assertTrue(CharMatcher.DIGIT.collapseFrom("Hello 1234 567", 'x').equals("Hello x x"));  
  87. }  
  88.   
  89. @Test  
  90. public void testReplaceFrom() {  
  91.    assertTrue(CharMatcher.DIGIT.replaceFrom("Hello 1234 567", 'x').equals("Hello xxxx xxx"));  
  92. }  
  93.   
  94. @Test  
  95. public void testCountIn() {  
  96.    assertTrue(CharMatcher.DIGIT.countIn("Hello 1234 567") == 7);  
  97. }  
  98.   
  99. @Test  
  100. public void testIndexIn() {  
  101.    assertTrue(CharMatcher.WHITESPACE.indexIn("Hello 1234 567") == 5);  
  102. }  
  103.   
  104. @Test  
  105. public void testLastIndexIn() {  
  106.    assertTrue(CharMatcher.WHITESPACE.lastIndexIn("Hello 1234 567") == 10);  
  107. }  
  108.   
  109. @Test  
  110. public void testRemoveFrom() {  
  111.    assertTrue(CharMatcher.inRange('3', '6').removeFrom("Hello 1234 567").equals("Hello 12 7"));  
  112. }  
  113.   
  114. @Test  
  115. public void testInRangeNegate() {  
  116.    assertTrue(CharMatcher.inRange('3', '6').negate().removeFrom("Hello 1234 567").equals("3456"));  
  117. }  
  118.   
  119. b.部分源码  
  120. public static CharMatcher anyOf(final CharSequence sequence) {  
  121.   switch (sequence.length()) {  
  122.     case 0:  
  123.       return NONE;  
  124.     case 1:  
  125.       return is(sequence.charAt(0));  
  126.     case 2:  
  127.       final char match1 = sequence.charAt(0);  
  128.       final char match2 = sequence.charAt(1);  
  129.       return new CharMatcher() {  
  130.         @Override public boolean matches(char c) {  
  131.           return c == match1 || c == match2;  
  132.         }  
  133.   
  134.         @Override public CharMatcher precomputed() {  
  135.           return this;  
  136.         }  
  137.       };  
  138.   }  
  139.   
  140.   final char[] chars = sequence.toString().toCharArray();  
  141.   Arrays.sort(chars); // not worth collapsing duplicates  
  142.   
  143.   return new CharMatcher() {  
  144.     @Override public boolean matches(char c) {  
  145.       return Arrays.binarySearch(chars, c) >= 0;  
  146.     }  
  147.   };  
  148. }  
  149.   
  150. public static final CharMatcher JAVA_DIGIT = new CharMatcher() {  
  151.   @Override public boolean matches(char c) {  
  152.     return Character.isDigit(c);  
  153.   }  
  154. };  
  155.   
  156. public static final CharMatcher JAVA_ISO_CONTROL =  
  157.     inRange('u0000', 'u001f').or(inRange('u007f', 'u009f'));  

使用Predicate实现集合过滤功能

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. //用来过滤符合条件的元素  
  2. Person person1 = new Person("zhangsan", 1, 25);  
  3. Person person2 = new Person("lisi", 0, 30);  
  4. Person person3 = new Person(null, 1, 25);  
  5. Person person4 = null;  
  6. List<Person> persons = Lists  
  7.       .newArrayList(person1, person2, person3, person4);  
  8.   
  9. public void testPredicte() {  
  10.    Iterable<Person> personsIter = Iterables  
  11.          .filter(persons, new Predicate<Person>() {  
  12.             public boolean apply(Person input) {  
  13.                return input != null && input.getAge() > 18;  
  14.             }  
  15.          });  
  16.    System.out.println(personsIter.toString());  
  17.    Collection<Person> filterCollection = Collections2  
  18.          .filter(persons, new Predicate<Person>() {  
  19.             public boolean apply(Person input) {  
  20.                return input != null && input.getAge() > 18;  
  21.             }  
  22.          });  
  23.   
  24.    System.out.println(filterCollection.toString());  
  25.   
  26.   
  27. }  
  28.   
  29. public void testPredicates() {  
  30.    List<String> colors = Lists  
  31.          .newArrayList("red", "blue", "green", "purple", "yellow",  
  32.                "pink", "", null);  
  33.    Iterable<String> colorIter = Iterables.filter(colors, Predicates  
  34.          .and(Predicates.<String>notNull(),  
  35.                Predicates.containsPattern("pu")));  
  36.    System.out.println(colorIter.toString());  
  37. }  

使用Function实现集合转换功能

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. //将对象集合转换为字符串集合。  
  2. public void testFunction() {  
  3.    Collection<String> filterCollection = Collections2  
  4.          .transform(persons, new Function<Person, String>() {  
  5.             public String apply(Person person) {  
  6.                return null == person ?  
  7.                      "" :  
  8.                      null == person.getName() ?  
  9.                            "" :  
  10.                            person.getName();  
  11.             }  
  12.          });  
  13.    List<String> names = Lists.newArrayList(filterCollection);  
  14.    System.out.println(names.toString());  
  15. }  
  16.   
  17. //过滤空对象和空的对象字段,实现复函数类似的功能  
  18. public void testFunctions() {  
  19.    Function<Person, String> getNameFunction = new Function<Person, String>() {  
  20.       public String apply(Person person) {  
  21.          return null == person.getName() ? "" : person.getName();  
  22.       }  
  23.    };  
  24.    Predicate<CharSequence> strFilter = Predicates.containsPattern("li");  
  25.    ImmutableList<String> names = FluentIterable.from(persons)  
  26.          .filter(Predicates.<Person>notNull()).transform(getNameFunction)  
  27.          .filter(strFilter).toList();  
  28.    System.out.println(names.toString());  
  29. }  
  30.    
  31. 像Lists和Maps这类的Collection工具类给我们提供了转换的方法:  
  32. topMap = Maps.transformValues(fromMap, function);  
  33. toList = Lists.transform(fromList, function);  
  34. public void testMapsTransformFromValues() {  
  35.     Map<String, Integer> rmbNameMoneyMapper = ImmutableMap.of("zhangsan", 100, "lisi", 80, "wangwu", 40);  
  36.     System.out.println(Joiner.on('|').withKeyValueSeparator(':').join(rmbNameMoneyMapper));  
  37.     Map<String, Double> dolorNameMoneyMapper = Maps.transformValues(rmbNameMoneyMapper, new Function<Integer, Double>() {  
  38.         public Double apply(Integer input) {  
  39.             if(input == null) {  
  40.                 return -1.0;  
  41.             }  
  42.             return input / 6.67;  
  43.         }  
  44.     });  
  45.     System.out.println(Joiner.on('|').withKeyValueSeparator(':').join(dolorNameMoneyMapper));  
  46. }  
  47. 结果:  
  48. //zhangsan:100|lisi:80|wangwu:40  
  49. //zhangsan:14.992503748125937|lisi:11.99400299850075|wangwu:5.997001499250375  
  50.    
  51. public void testListsTransformFrom() {  
  52.     List<Double> rmbMoneyList = Lists.newArrayList(100.9, 80.0, 40.0, 20.9);  
  53.     System.out.println(Joiner.on(',').skipNulls().join(rmbMoneyList));  
  54.     List<Double> dollarMoneyList = Lists.transform(rmbMoneyList, new Function<Double, Double>() {  
  55.         public Double apply(Double input) {  
  56.             return input / 6.67;  
  57.         }  
  58.     });  
  59.     System.out.println(Joiner.on(',').skipNulls().join(dollarMoneyList));  
  60. }  
  61. 结果:  
  62. //100.9,80.0,40.0,20.9  
  63. //15.12743628185907,11.99400299850075,5.997001499250375,3.1334332833583205  

使用Joinner拼接字符串

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. //测试Joinner类  
  2.   public void testJoinner() {  
  3.     List<String> colors = Lists.newArrayList("red", "blue", "green", "purple", "yellow", "pink", "", null);  
  4. //    String colorStr = Joiner.on(',').useForNull("no color").skipNulls().join(colors);  
  5.     String colorStr = Joiner.on(',').useForNull("no color").join(colors);  
  6.     System.out.println(colorStr);  
  7.   }  
  8.   
  9.   public void testMapJoinner() {  
  10.     Map<String,String> cityDistMapper = ImmutableMap.of("海淀区", "北京", "朝阳区", "北京", "昌平区", "北京");  
  11.     String cityDistMapperStr = Joiner.on("|").withKeyValueSeparator("-").join(cityDistMapper);  
  12.     System.out.println(cityDistMapperStr);  
  13.   }  
  14.   
  15. //Joinner部分源码  
  16.   public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {  
  17.     checkNotNull(appendable);  
  18.     if (parts.hasNext()) {  
  19.       appendable.append(toString(parts.next()));  
  20.       while (parts.hasNext()) {  
  21.         appendable.append(separator);  
  22.         appendable.append(toString(parts.next()));  
  23.       }  
  24.     }  
  25.     return appendable;  
  26.   }  
  27.   
  28. //优雅避免,用自有的toString方法可方便进行useForNull,否则会出现s异常  
  29.   @CheckReturnValue  
  30.   public Joiner useForNull(final String nullText) {  
  31.     checkNotNull(nullText);  
  32.     return new Joiner(this) {  
  33.       @Override  
  34.       CharSequence toString(@Nullable Object part) {  
  35.         return (part == null) ? nullText : Joiner.this.toString(part);  
  36.       }  
  37.       @Override  
  38.       public Joiner useForNull(String nullText) {  
  39.         throw new UnsupportedOperationException("already specified useForNull");  
  40.       }  
  41.   
  42.       @Override  
  43.       public Joiner skipNulls() {  
  44.         throw new UnsupportedOperationException("already specified useForNull");  
  45.       }  
  46.     };  
  47.   }  
  48.   
  49.   @CheckReturnValue  
  50.   public Joiner skipNulls() {  
  51.     return new Joiner(this) {  
  52.       @Override  
  53.       public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {  
  54.         checkNotNull(appendable, "appendable");  
  55.         checkNotNull(parts, "parts");  
  56.         while (parts.hasNext()) {  
  57.           Object part = parts.next();  
  58.           if (part != null) {  
  59.             appendable.append(Joiner.this.toString(part));  
  60.             break;  
  61.           }  
  62.         }  
  63.         while (parts.hasNext()) {  
  64.           Object part = parts.next();  
  65.           if (part != null) {  
  66.             appendable.append(separator);  
  67.             appendable.append(Joiner.this.toString(part));  
  68.           }  
  69.         }  
  70.         return appendable;  
  71.       }  
  72.   
  73.       @Override  
  74.       public Joiner useForNull(String nullText) {  
  75.         throw new UnsupportedOperationException("already specified skipNulls");  
  76.       }  
  77.   
  78.       @Override  
  79.       public MapJoiner withKeyValueSeparator(String kvs) {  
  80.         throw new UnsupportedOperationException("can't use .skipNulls() with maps");  
  81.       }  
  82.     };  
  83.   
  84.   
  85.   }  

使用Splitter拆分字符串

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. //Splitter类测试代码  
  2. public void testMapSppliter() {  
  3.   Map<String,String> cityDistMapper = Maps.newHashMap();  
  4.   String beijingDistricts = " 海淀区:北京|   朝阳区:北京| 东城区:北京 ||西城区:北京|昌平区:北京  |   |";  
  5.   cityDistMapper.putAll(Splitter.on("|").omitEmptyStrings().trimResults().withKeyValueSeparator(":").split(beijingDistricts));  
  6.   System.out.println(cityDistMapper.entrySet().toString());  
  7. }  
  8.   
  9. public void testSppliter() {  
  10.   String colorStrs = "red,blue  ,green, purple, yellow ,pink,  ,   ,";  
  11.   List<String> colors = Lists.newArrayList(Splitter.on(',').omitEmptyStrings().trimResults().split(colorStrs));  
  12.   System.out.println(colors.toString());  
  13.   
  14.   
  15. //Splitter部分源码  
  16.   @CheckReturnValue  
  17.   public static Splitter on(final String separator) {  
  18.     checkArgument(separator.length() != 0, "The separator may not be the empty string.");  
  19.     if (separator.length() == 1) {  
  20.       return Splitter.on(separator.charAt(0));  
  21.     }  
  22.   
  23.     return new Splitter(  
  24.         new Strategy() {  
  25.           @Override  
  26.           public SplittingIterator iterator(Splitter splitter, CharSequence toSplit) {  
  27.             return new SplittingIterator(splitter, toSplit) {  
  28.               @Override  
  29.               public int separatorStart(int start) {  
  30.                 int separatorLength = separator.length();  
  31.   
  32.                 positions:  
  33.                 for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) {  
  34.                   for (int i = 0; i < separatorLength; i++) {  
  35.                     if (toSplit.charAt(i + p) != separator.charAt(i)) {  
  36.                       continue positions;  
  37.                     }  
  38.                   }  
  39.                   return p;  
  40.                 }  
  41.                 return -1;  
  42.               }  
  43.   
  44.               @Override  
  45.               public int separatorEnd(int separatorPosition) {  
  46.                 return separatorPosition + separator.length();  
  47.               }  
  48.             };  
  49.           }  
  50.         });  
  51.   }  
  52.   
  53.   
  54.     @Override  
  55.     protected String computeNext() {  
  56.       /* 
  57.        * The returned string will be from the end of the last match to the 
  58.        * beginning of the next one. nextStart is the start position of the 
  59.        * returned substring, while offset is the place to start looking for a 
  60.        * separator. 
  61.        */  
  62.   
  63.       int nextStart = offset;  
  64.       while (offset != -1) {  
  65.         int start = nextStart;  
  66.         int end;  
  67.         int separatorPosition = separatorStart(offset);  
  68.         if (separatorPosition == -1) {  
  69.           end = toSplit.length();  
  70.           offset = -1;  
  71.         } else {  
  72.           end = separatorPosition;  
  73.           offset = separatorEnd(separatorPosition);  
  74.         }  
  75.   
  76.         if (offset == nextStart) {  
  77.           /* 
  78.            * This occurs when some pattern has an empty match, even if it 
  79.            * doesn't match the empty string -- for example, if it requires 
  80.            * lookahead or the like. The offset must be increased to look for 
  81.            * separators beyond this point, without changing the start position 
  82.            * of the next returned substring -- so nextStart stays the same. 
  83.            */  
  84.           offset++;  
  85.           if (offset >= toSplit.length()) {  
  86.             offset = -1;  
  87.           }  
  88.           continue;  
  89.         }  
  90.   
  91.         while (start < end && trimmer.matches(toSplit.charAt(start))) {  
  92.           start++;  
  93.         }  
  94.         while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {  
  95.           end--;  
  96.         }  
  97.   
  98.         if (omitEmptyStrings && start == end) {  
  99.           // Don't include the (unused) separator in next split string.  
  100.           nextStart = offset;  
  101.           continue;  
  102.         }  
  103.   
  104.         if (limit == 1) {  
  105.           // The limit has been reached, return the rest of the string as the  
  106.           // final item.  This is tested after empty string removal so that  
  107.           // empty strings do not count towards the limit.  
  108.           end = toSplit.length();  
  109.           offset = -1;  
  110.   
  111.          // Since we may have changed the end, we need to trim it again.  
  112.           while (end > start && trimmer.matches(toSplit.charAt(end - 1))) {  
  113.             end--;  
  114.           }  
  115.         } else {  
  116.           limit--;  
  117.         }  
  118.         return toSplit.subSequence(start, end).toString();  
  119.       }  
  120.       return endOfData();  
  121.     }  

MultiSet和MultiMap的使用场景

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. a.MultiMap的使用,主要用来统计  
  2. public void testHashMultiMap() {  
  3.    Multimap<String, String> multimap = HashMultimap.create();  
  4.    String beijingDistricts = "海淀区| 海淀区 | 朝阳区|东城区 ||西城区|昌平区";  
  5.    String shanghaiDistricts = "静安区 |徐汇区|   | 浦东区|普陀区|  |崇明区";  
  6.    multimap.putAll("北京", Splitter.on('|').omitEmptyStrings().trimResults().split(beijingDistricts));  
  7.    multimap.putAll("上海", Splitter.on('|').omitEmptyStrings().trimResults().split(shanghaiDistricts));  
  8.    System.out.println(multimap.toString());  
  9.    assertTrue(multimap.get("北京").toString().equals("[朝阳区, 西城区, 东城区, 海淀区, 昌平区]"));  
  10.    multimap.remove("北京", "东城区");  
  11.    assertTrue(multimap.get("北京").toString().equals("[朝阳区, 西城区, 海淀区, 昌平区]"));  
  12. }  
  13.   
  14. public void testArrayListMultimap() {  
  15.    Multimap<String, String> multimap = ArrayListMultimap.create();  
  16.    String beijingDistricts = "海淀区| 海淀区 | 朝阳区|东城区 ||西城区|昌平区";  
  17.    String shanghaiDistricts = "静安区 |徐汇区|   | 浦东区|普陀区|  |崇明区";  
  18.    multimap.putAll("北京", Splitter.on('|').omitEmptyStrings().trimResults().split(beijingDistricts));  
  19.    multimap.putAll("上海", Splitter.on('|').omitEmptyStrings().trimResults().split(shanghaiDistricts));  
  20.    Map<String, Collection<String>> cityDistMapper = multimap.asMap();  
  21.    System.out.println(multimap.toString());  
  22.    assertTrue(multimap.get("北京").toString().equals("[海淀区, 海淀区, 朝阳区, 东城区, 西城区, 昌平区]"));  
  23.    multimap.remove("北京", "东城区");  
  24.    assertTrue(multimap.get("北京").toString().equals("[海淀区, 海淀区, 朝阳区, 西城区, 昌平区]"));  
  25. }  
  26.   
  27. b.MultiSet的使用,主要用来计数  
  28. public void testHashMultiSet() {  
  29.    String colorStr = "red|blue|yellow |green| red|purple|red|yellow|blue |blue|blue|green||blue";  
  30.    List<String> colorStrs = Lists.newArrayList(Splitter.on('|').omitEmptyStrings().trimResults().split(colorStr));  
  31.    Multiset<String> countStrs = HashMultiset.create();  
  32.    countStrs.addAll(colorStrs);  
  33.    StringBuilder stringBuilder = new StringBuilder("");  
  34.    for (String color : countStrs.elementSet()) {  
  35.       stringBuilder.append(color + ":" + countStrs.count(color) + "|");  
  36.    }  
  37.    assertTrue(stringBuilder.toString().equals("red:3|purple:1|blue:5|green:2|yellow:2|"));  
  38. }  

几个常用工具类

[java] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. 1.lists和maps操作  
  2. ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d");  
  3. ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");  
  4. Lists.newArrayList(),Maps.newHashMap();  
  5.   
  6. 2.比较数字  
  7. int compare = Ints.compare(a, b);  
  8. int compare = Doubles.compare(a,b);  
  9.   
  10. 3.数组操作  
  11. Ints.toArray();  
  12. Ints.asList(numbers);  
  13. boolean contains = Ints.contains(array, a);  
  14. int indexOf = Ints.indexOf(array, a);  
  15. int max = Ints.max(array);  
  16. int min = Ints.min(array);  
  17. int[] concat = Ints.concat(array, array2);   
  18.   
  19. 4.Iterables,Collections2  
  20. Collections2的filter、transform方法  
  21. Iterables的filter、transform等方法  
  22. Iterables.all(list,predicateObject)  
  23.   
  24. 5.使用Guava的选择和预判断使得代码更简洁,过多的if else return使代码看起来很不美观。  
  25. public void doSomething( List<Object> list ) {  
  26.   if( list == null ) {  
  27.     throw new IllegalArgumentException( "List must not be null" );  
  28.   }  
  29.   if( list.isEmpty() ) {  
  30.     throw new IllegalArgumentException( "List must not be empty" );  
  31.   }  
  32.   doSomethingMore( list );  
  33. }  
  34. 使用Guava的预判断后的代码,参数有问题尽快失败。  
  35. public void doSomething( List<Object> list ) {  
  36.   checkArgument( list != null, "List must not be null" );  
  37.   checkArgument( !list.isEmpty(), "List must not be empty" );  
  38.   doSomethingMore( list );  
  39. }  
  40.    
  41. 1).checkArgument(boolean) :  
  42. 功能描述:检查boolean是否为真。 用作方法中检查参数  
  43. 失败时抛出的异常类型: IllegalArgumentException  
  44.   
  45. 2).checkNotNull(T):  
  46. 功能描述:检查value不为null, 直接返回value;  
  47. 失败时抛出的异常类型:NullPointerException  
  48.   
  49. 3).checkState(boolean):  
  50. 功能描述:检查对象的一些状态,不依赖方法参数。 例如, Iterator可以用来next是否在remove之前被调用。  
  51. 失败时抛出的异常类型:IllegalStateException  
  52.    
  53. public void testCheckArgument() {  
  54.    Preconditions.checkArgument(false);  
  55. }  
  56.   
  57. public void testCheckArgumentWithMessage() {  
  58.    Preconditions.checkArgument(false, "hello");  
  59. }  
  60.   
  61. public void testCheckState_simple_success() {  
  62.    Preconditions.checkState(true);  
  63. }  
  64.   
  65. public void testCheckStateWithMessage() {  
  66.    Preconditions.checkState(false, "checkState false");  
  67. }  
  68.   
  69. private static final String NON_NULL_STRING = "hello world";  
  70.   
  71.   
  72. public void testCheckNotNull_simple_success() {  
  73.    String result = Preconditions.checkNotNull(NON_NULL_STRING);  
  74.    assertSame(NON_NULL_STRING, result);  
  75. }  
  76.   
  77. public void testCheckNotNull() {  
  78.    Preconditions.checkNotNull(null);  
  79. }  
  80.   
  81. public void testCheckNotNullWithMessage() {  
  82.    String nullNameStr = "I'm null";  
  83.    String result = Preconditions.checkNotNull(null, nullNameStr);  
  84. }  
  85. 6.Strings   
  86. nulltoEmpty(),emptyToNull(),isNullOrEmpty(),commonPrefix(),commonSuffix(),  
  87. paddingStart(),paddingEnd(),repeat()这几个方法。  
  88. public void testPadStart() {  
  89.    assertEquals("-", Strings.padStart("", 1, '-'));  
  90.    assertEquals("--", Strings.padStart("", 2, '-'));  
  91.    assertEquals("-x", Strings.padStart("x", 2, '-'));  
  92.    assertEquals("--x", Strings.padStart("x", 3, '-'));  
  93.    assertEquals("-xx", Strings.padStart("xx", 3, '-'));  
  94. }  
  95.   
  96. public void testRepeat() {  
  97.    String input = "20";  
  98.    assertEquals("", Strings.repeat(input, 0));  
  99.    assertEquals("20", Strings.repeat(input, 1));  
  100.    assertEquals("2020", Strings.repeat(input, 2));  
  101.    assertEquals("202020", Strings.repeat(input, 3));  
  102. }  
  103.    
  104. public void testCommonPrefix() {  
  105.    assertEquals("", Strings.commonPrefix("", "abc"));  
  106.    assertEquals("", Strings.commonPrefix("xyz", "abcxyz"));  
  107.    assertEquals("a", Strings.commonPrefix("abc", "aaaaa"));  
  108.    assertEquals("aa", Strings.commonPrefix("aa", "aaaaa"));  
  109. }  
  110.    
  111. public static String repeat(String string, int count) {  
  112.   checkNotNull(string); // eager for GWT.  
  113.   
  114.   if (count <= 1) {  
  115.     checkArgument(count >= 0, "invalid count: %s", count);  
  116.     return (count == 0) ? "" : string;  
  117.   }  
  118.   
  119.   // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark  
  120.   final int len = string.length();  
  121.   final long longSize = (long) len * (long) count;  
  122.   final int size = (int) longSize;  
  123.   if (size != longSize) {  
  124.     throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize);  
  125.   }  
  126.   
  127.   final char[] array = new char[size];  
  128.   string.getChars(0, len, array, 0);  
  129.   int n;  
  130.   for (n = len; n < size - n; n <<= 1) {  
  131.     System.arraycopy(array, 0, array, n, n);  
  132.   }  
  133.   System.arraycopy(array, 0, array, n, size - n);  
  134.   return new String(array);  
  135. }  
原文地址:https://www.cnblogs.com/zhongshiqiang/p/6846292.html