Guava ---- 基础工具篇

    使用现成的库的原因, 既能减少自己开发所带来的bug, 同时又大大提高了开发效率, 当然这也是Java语言流行的一个原因----拥有海量的开源包。

    本篇从Guava基础工具入手开始介绍这个广泛使用的库:

package com.wenniuwuren.guava;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;

import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.ComparisonChain;

import sun.org.mozilla.javascript.internal.ast.TryStatement;

/**
 * 
 * @ClassName: WorkingWithStrings 
 * @Description: 对字符串的操作
 * @author wenniuwuren 
 * @date 2015-5-20 上午11:33:59 
 *
 */
public class WorkingWithStrings {
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		
	     // 问题: 1."UTF-8"必须在Java平台中被支持    2.人工敲入会有偏差
		 // byte[] bytes = "foo".getBytes("UTF-8");
		 // 解决: Charsets类提供了对Java平台支持字符集
		 byte[] bytes = "foo".getBytes(Charsets.UTF_8);
		 
		 
		 // 问题: 使用StringBuilder类连接字符串太繁琐, 代码其实都是重复的
		 // 解决: Strings类封装了连接字符串的统一代码
		 System.out.println("padEnd");
		 String stringsTest = Strings.padEnd("foo", 6, 'o');
		 System.out.println(stringsTest);
		 
		 // 在String作为参数时,将null转换成""防止空指针问题 
		 System.out.println("nullToEmpty");
		 String nullToEmptyTest1 = Strings.nullToEmpty("123");
		 String nullToEmptyTest2 = Strings.nullToEmpty(null);
		 System.out.println(nullToEmptyTest1 + "--" + nullToEmptyTest2);
		 
		 // ""转null
		 System.out.println("emptyToNull");
		 String emptyToNullTest1 = Strings.emptyToNull("123");
		 String emptyToNullTest2 = Strings.emptyToNull("");
		 System.out.println(emptyToNullTest1 + "--" + emptyToNullTest2);
		 
		 // 将字符串中的Tab和多个空格转为一个空格
		 String tabsAndSpaces = "String with   spaces	and	tabs";
		 String expected = "String with spaces and tabs";
		 String scrubbed = CharMatcher.WHITESPACE.collapseFrom(tabsAndSpaces,' ');
		 System.out.println(expected.equals(scrubbed));
		 
		 
		 
		 // Object utilities 对象工具
		 // 1. toString()实现
		 System.out.println(Objects.toStringHelper(WorkingWithStrings.class).omitNullValues()
				 .add("expected", expected).add("tabsAndSpaces", tabsAndSpaces));
		 
		 // 2. 检查如果为null值 , 填充默认值
		 System.out.println(Objects.firstNonNull(null, "default value"));
		 
		 // 3. 生成hashcode
		 System.out.println(Objects.hashCode(tabsAndSpaces, expected));
		 
		 // 4. CompareTo实现    如果都是相同的返回0,有一个不同返回-1
		 System.out.println(ComparisonChain.start().compare(tabsAndSpaces, expected).compare(expected, scrubbed).result());
	}
	
}


参考资料:

               《Getting Started with Google Guava》

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值