走近Guava(一): 基本工具

基本工具:

使用Joiner类:

  • 例如我们想将字符串列表通过一个分隔符链接起来,以前的方式就是迭代append等操作,使用Joiner可以更方便。
  • Joiner一旦创建不可变,符合不变性,因此线程安全

看一些测试用例:

  • 链接字符串列表
String delimiter = ",";
// Joiner类一旦创建则不可变,满足不可变性,因此线程安全
Joiner joiner = Joiner.on(delimiter);
		
// 忽略null
String excludeNullString = joiner.skipNulls().join(langs);
// 将null替代为empty字符串
String replaceNullString = joiner.useForNull("empty").join(langs);
System.out.println("excludeNullString: " + excludeNullString);
System.out.println("replaceNullString: " + replaceNullString);
		
// 不对null处理,默认会抛NullPointerException
String defaultNullString = joiner.join(langs); //langs为List<String>
System.out.println("defaultNullString: " + defaultNullString);
  • 链接多个字符串
String delimiter = ",";
// Joiner类一旦创建则不可变,满足不可变性,因此线程安全
Joiner joiner = Joiner.on(delimiter).skipNulls();
//joiner.useForNull("empty"); //重复定义null操作会抛异常
String res = joiner.join(null, "foo","bar");
System.out.println(res); //foo,bar
  • appendTo到实现了Appendable接口的类中:
//append到StringBuilder
StringBuilder stringBuilder = new StringBuilder();
Joiner joiner = Joiner.on(",").skipNulls();
joiner.appendTo(stringBuilder, "appendTo", "StringBuilder");
System.out.println(stringBuilder); //appendTo,StringBuilder
		
//append到输出流
FileWriter writer = new FileWriter("append_text.txt");
joiner.appendTo(writer, "appendTo", "FileWriter");
writer.close();
  • 通过MapJoiner链接Map对象:
Map<String, String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
MapJoiner mapJoiner = Joiner.on(",").withKeyValueSeparator("=");
String str = mapJoiner.join(map);
System.out.println(str);//结果如:key3=value3,key2=value2,key1=value1

使用Splitter类:

  • Splitter功能与Joiner相反,其对字符串进行分割操作
  • 分割字符串,返回Iterable<String>对象:
String str = "try ,do , your , best";
Splitter splitter = Splitter.on(",").trimResults(); //用逗号分割且去掉每个字符串周围的空格
//splitter.trimResults(); //这样是不会去掉各个元素空格的, 它仅返回一个新的Splitter
Iterable<String> res = splitter.split(str);
System.out.println(res); //[try, do, your, best]
  • 使用MapSplitter分割字符串,返回Map<String, String>对象:
String str = "key3=value3,key2=value2,key1=value1";
MapSplitter splitter = Splitter.on(",").withKeyValueSeparator("=");
Map<String, String> map = splitter.split(str);
System.out.println(map);// {key3=value3, key2=value2, key1=value1}

使用Strings类:

  • Strings类有用的API:
//用padChar填充string后面, 使string最小长度为minLength
padEnd(String string, int minLength, char padChar)
//用padChar填充string前面, 使string最小长度为minLength
padStart(String string, int minLength, char padChar)
//null转换为""
nullToEmpty(String string)
//""转换为null
emptyToNull(String string)
//true, 如果字符串为null或者""
isNullOrEmpty(Strng string)

使用CharMatcher类:

  • 替换多个连续的空格为单个空格
String tabsAndSpaces = "String  with      spaces     and tabs";
//将多个连续的空格替换为一个
String scrubbed = CharMatcher.WHITESPACE.collapseFrom(tabsAndSpaces,' ');
System.out.println(scrubbed); //String with spaces and tabs
  • 有时我们还想将头尾的空格去掉
String tabsAndSpaces = "    String  with     spaces     and tabs";
String scrubbed = CharMatcher.WHITESPACE.trimAndCollapseFrom(tabsAndSpaces, ' ');
System.out.println(scrubbed); //String with spaces and tabs
  • 保留制定字符,如数字,字母等:
String lettersAndNumbers = "foo989yxbar234";
String retained = CharMatcher.JAVA_DIGIT.retainFrom(lettersAndNumbers); //保留数字
System.out.println(retained); //989234
  • 你也可以通过Or组合多个CharMatcher:
CharMatcher cm = CharMatcher.JAVA_DIGIT.or(CharMatcher.WHITESPACE);
String retained = cm.retainFrom("foo9 89y xbar 234");//保留数字和空格
System.out.println(retained); //9 89  234

使用Preconditions类:

  • 这是一个用于判断条件的一个工具,类似junit中Aseert功能。
checkNotNull(obj, "检查对象不能为空");
checkElementIndex(index, arr.length,"检查数组索引");
checkArgument(valueToSet <= 100, "检查参数值");
checkState(validateObjectState(), "检查对象状态");

使用Objects类:

  • toString方法的使用。
public class Book implements Comparable<Book> {
	private Person author;
	private String title;
	private String publisher;
	private String isbn;
	private double price;
	...
	@Override
	public int compareTo(Book o) { 
		 return ComparisonChain.start() //链式比较,在第一个非0处返回
                 .compare(this.title, o.getTitle())
                 .compare(this.author, o.getAuthor())
                 .compare(this.publisher, o.getPublisher())
                 .compare(this.isbn, o.getIsbn())
                 .compare(this.price, o.getPrice())
                 .result();
	}
	
	@Override
	public int hashCode(){
		return Objects.hashCode(title, author, publisher, isbn);//hashCode生成
	}

	@Override
	public String toString() {
		return Objects.toStringHelper(this) //toString
                .omitNullValues() //忽略null属性
                .add("title", title)
                .add("author", author)
                .add("publisher", publisher)
                .add("price",price)
                .add("isbn", isbn).toString();
	}
}
  • 获取非null默认值
String str = null;
str = Objects.firstNonNull(str, "defaut value");
System.out.println(str);

以上就是基本工具使用。

不吝指正。

你可能感兴趣的:(guava,基本工具)