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

Objects类

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

排序的实现和改进

  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. public void testOrderingWithComparisonChain() {
  8. assertTrue(persons.toString().equals("[Person{name=zhangsan, sex=1, age=25}, Person{name=lisi, sex=0, age=30}, Person{sex=1, age=25}, null]"));
  9. System.out.println(persons.toString());
  10. Ordering<Person> personOrdering = new Ordering<Person>() {
  11. @Override
  12. public int compare(Person p1, Person p2) {
  13. return ComparisonChain.start().compare(p1.getAge(), p2.getAge())
  14. .compare(p1.getName(), p2.getName())
  15. .compare(p1.getSex(), p2.getSex()).result();
  16. }
  17. }.nullsFirst();
  18. Collections.sort(persons, personOrdering);
  19. System.out.println(persons.toString());
  20. //Collections.sort(persons, personOrdering.reverse());
  21. }
  22. public void testOrderingWithComparator() {
  23. System.out.println(persons.toString());
  24. Collections.sort(persons, new Comparator<Person>() {
  25. public int compare(Person p1, Person p2) {
  26. return ComparisonChain.start().compare(p1.getAge(), p2.getAge())
  27. .compare(p1.getName(), p2.getName())
  28. .compare(p1.getSex(), p2.getSex()).result();
  29. }
  30. });
  31. System.out.println(persons.toString());
  32. }

CharMatcher

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

使用Predicate实现集合过滤功能

  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. public void testPredicte() {
  9. Iterable<Person> personsIter = Iterables
  10. .filter(persons, new Predicate<Person>() {
  11. public boolean apply(Person input) {
  12. return input != null && input.getAge() > 18;
  13. }
  14. });
  15. System.out.println(personsIter.toString());
  16. Collection<Person> filterCollection = Collections2
  17. .filter(persons, new Predicate<Person>() {
  18. public boolean apply(Person input) {
  19. return input != null && input.getAge() > 18;
  20. }
  21. });
  22. System.out.println(filterCollection.toString());
  23. }
  24. public void testPredicates() {
  25. List<String> colors = Lists
  26. .newArrayList("red", "blue", "green", "purple", "yellow",
  27. "pink", "", null);
  28. Iterable<String> colorIter = Iterables.filter(colors, Predicates
  29. .and(Predicates.<String>notNull(),
  30. Predicates.containsPattern("pu")));
  31. System.out.println(colorIter.toString());
  32. }

使用Function实现集合转换功能

  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. public void testFunctions() {
  18. Function<Person, String> getNameFunction = new Function<Person, String>() {
  19. public String apply(Person person) {
  20. return null == person.getName() ? "" : person.getName();
  21. }
  22. };
  23. Predicate<CharSequence> strFilter = Predicates.containsPattern("li");
  24. ImmutableList<String> names = FluentIterable.from(persons)
  25. .filter(Predicates.<Person>notNull()).transform(getNameFunction)
  26. .filter(strFilter).toList();
  27. System.out.println(names.toString());
  28. }
  29. 像Lists和Maps这类的Collection工具类给我们提供了转换的方法:
  30. topMap = Maps.transformValues(fromMap, function);
  31. toList = Lists.transform(fromList, function);
  32. public void testMapsTransformFromValues() {
  33. Map<String, Integer> rmbNameMoneyMapper = ImmutableMap.of("zhangsan", 100, "lisi", 80, "wangwu", 40);
  34. System.out.println(Joiner.on('|').withKeyValueSeparator(':').join(rmbNameMoneyMapper));
  35. Map<String, Double> dolorNameMoneyMapper = Maps.transformValues(rmbNameMoneyMapper, new Function<Integer, Double>() {
  36. public Double apply(Integer input) {
  37. if(input == null) {
  38. return -1.0;
  39. }
  40. return input / 6.67;
  41. }
  42. });
  43. System.out.println(Joiner.on('|').withKeyValueSeparator(':').join(dolorNameMoneyMapper));
  44. }
  45. 结果:
  46. //zhangsan:100|lisi:80|wangwu:40
  47. //zhangsan:14.992503748125937|lisi:11.99400299850075|wangwu:5.997001499250375
  48. public void testListsTransformFrom() {
  49. List<Double> rmbMoneyList = Lists.newArrayList(100.9, 80.0, 40.0, 20.9);
  50. System.out.println(Joiner.on(',').skipNulls().join(rmbMoneyList));
  51. List<Double> dollarMoneyList = Lists.transform(rmbMoneyList, new Function<Double, Double>() {
  52. public Double apply(Double input) {
  53. return input / 6.67;
  54. }
  55. });
  56. System.out.println(Joiner.on(',').skipNulls().join(dollarMoneyList));
  57. }
  58. 结果:
  59. //100.9,80.0,40.0,20.9
  60. //15.12743628185907,11.99400299850075,5.997001499250375,3.1334332833583205

使用Joinner拼接字符串

  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. public void testMapJoinner() {
  9. Map<String,String> cityDistMapper = ImmutableMap.of("海淀区", "北京", "朝阳区", "北京", "昌平区", "北京");
  10. String cityDistMapperStr = Joiner.on("|").withKeyValueSeparator("-").join(cityDistMapper);
  11. System.out.println(cityDistMapperStr);
  12. }
  13. //Joinner部分源码
  14. public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
  15. checkNotNull(appendable);
  16. if (parts.hasNext()) {
  17. appendable.append(toString(parts.next()));
  18. while (parts.hasNext()) {
  19. appendable.append(separator);
  20. appendable.append(toString(parts.next()));
  21. }
  22. }
  23. return appendable;
  24. }
  25. //优雅避免,用自有的toString方法可方便进行useForNull,否则会出现s异常
  26. @CheckReturnValue
  27. public Joiner useForNull(final String nullText) {
  28. checkNotNull(nullText);
  29. return new Joiner(this) {
  30. @Override
  31. CharSequence toString(@Nullable Object part) {
  32. return (part == null) ? nullText : Joiner.this.toString(part);
  33. }
  34. @Override
  35. public Joiner useForNull(String nullText) {
  36. throw new UnsupportedOperationException("already specified useForNull");
  37. }
  38. @Override
  39. public Joiner skipNulls() {
  40. throw new UnsupportedOperationException("already specified useForNull");
  41. }
  42. };
  43. }
  44. @CheckReturnValue
  45. public Joiner skipNulls() {
  46. return new Joiner(this) {
  47. @Override
  48. public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException {
  49. checkNotNull(appendable, "appendable");
  50. checkNotNull(parts, "parts");
  51. while (parts.hasNext()) {
  52. Object part = parts.next();
  53. if (part != null) {
  54. appendable.append(Joiner.this.toString(part));
  55. break;
  56. }
  57. }
  58. while (parts.hasNext()) {
  59. Object part = parts.next();
  60. if (part != null) {
  61. appendable.append(separator);
  62. appendable.append(Joiner.this.toString(part));
  63. }
  64. }
  65. return appendable;
  66. }
  67. @Override
  68. public Joiner useForNull(String nullText) {
  69. throw new UnsupportedOperationException("already specified skipNulls");
  70. }
  71. @Override
  72. public MapJoiner withKeyValueSeparator(String kvs) {
  73. throw new UnsupportedOperationException("can't use .skipNulls() with maps");
  74. }
  75. };
  76. }

使用Splitter拆分字符串

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

MultiSet和MultiMap的使用场景

  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. public void testArrayListMultimap() {
  14. Multimap<String, String> multimap = ArrayListMultimap.create();
  15. String beijingDistricts = "海淀区| 海淀区 | 朝阳区|东城区 ||西城区|昌平区";
  16. String shanghaiDistricts = "静安区 |徐汇区|   | 浦东区|普陀区|  |崇明区";
  17. multimap.putAll("北京", Splitter.on('|').omitEmptyStrings().trimResults().split(beijingDistricts));
  18. multimap.putAll("上海", Splitter.on('|').omitEmptyStrings().trimResults().split(shanghaiDistricts));
  19. Map<String, Collection<String>> cityDistMapper = multimap.asMap();
  20. System.out.println(multimap.toString());
  21. assertTrue(multimap.get("北京").toString().equals("[海淀区, 海淀区, 朝阳区, 东城区, 西城区, 昌平区]"));
  22. multimap.remove("北京", "东城区");
  23. assertTrue(multimap.get("北京").toString().equals("[海淀区, 海淀区, 朝阳区, 西城区, 昌平区]"));
  24. }
  25. b.MultiSet的使用,主要用来计数
  26. public void testHashMultiSet() {
  27. String colorStr = "red|blue|yellow |green| red|purple|red|yellow|blue |blue|blue|green||blue";
  28. List<String> colorStrs = Lists.newArrayList(Splitter.on('|').omitEmptyStrings().trimResults().split(colorStr));
  29. Multiset<String> countStrs = HashMultiset.create();
  30. countStrs.addAll(colorStrs);
  31. StringBuilder stringBuilder = new StringBuilder("");
  32. for (String color : countStrs.elementSet()) {
  33. stringBuilder.append(color + ":" + countStrs.count(color) + "|");
  34. }
  35. assertTrue(stringBuilder.toString().equals("red:3|purple:1|blue:5|green:2|yellow:2|"));
  36. }

几个常用工具类

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

最新文章

  1. iftop 安装以及相关参数及说明(转载自csdn)
  2. transform你不知道的那些事
  3. easyui datagrid
  4. XidianOJ 1182 Chinese Paladin – Qi’s troubles
  5. Android自定义图片加载框架
  6. 微信小程序发布
  7. python3字符串
  8. 微信小程序统计分析
  9. python-并发初学
  10. Ubuntu14.04+ROS 启动本地摄像头
  11. 递归求6的阶乘(考虑int类型溢出)
  12. PVS桌面主镜像配置后,实际用户登录,配置未生效
  13. 用virsh console vhosts 卡住
  14. ios-密码判断
  15. 12.2、多线程通信:queue
  16. windows中的mysql修改管理员密码
  17. 基于Vue手写一个下拉刷新
  18. (转载)Oracle的悲观锁和乐观锁
  19. vue 获取数据联动下拉框select ,并解决报Duplicate value found in v-for=&quot;...&quot;: &quot;&quot;. Use track-by=&quot;$index&quot; 错误
  20. web开发之Servlet 二

热门文章

  1. MFC画标尺
  2. 如何让 ssh 允许以 root 身份登录
  3. 我的spark python 决策树实例
  4. 11.修改WSDL文档
  5. String不可变性
  6. rehat7.X下postgresql 11编译安装
  7. JAVA 常用集合接口List、Set、Map总结
  8. LeetCode Weekly Contest 22
  9. ES6变量的解构赋值
  10. 用命令行在本地创建一个库并上传到Github