google guava使用介绍
2016-07-18 09:12
543 查看
guava简介
Google Guava很优秀,大有取代Apache Commons之势。Guava是用来,用原汁原味的英文来说就是“Our goal is for you to write less code and for the code you do write to be simpler, cleaner, and more readable”,Guava中主要包括Basic Utilities,Collections,Caches,Functional Idioms,Concurrency,Strings,Primitives Support,Ranges,I/O等等。下面介绍一些它的简单使用例子:1、预先判断Preconditions
可以用在方法的开始或者是构造函数的开始,对于不合法的校验可以快速报错。
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; public class PreconditionsDemo { public static void main(String[] args) { new Car(null);//Exception in thread "main" java.lang.NullPointerException //Exception in thread "main" java.lang.IllegalArgumentException: speed (0.0) must be positive new Car("Audi").drive(0); } } class Car { private String name; public Car(String name) { this.name = checkNotNull(name);//NPE Null Pointer Exception } public void drive(double speed) { checkArgument(speed > 0.0, "speed (%s) must be positive", speed); } }
除了checkNotNull之外,Preconditions还提供了一些其他的方法,如chekArgument, checkState, checkElementIndex, checkPositionIndex等,更多可参考Preconditions API。
2、Object.toStringHelper()
这个方法主要是用于更加简单的实现Object.toString()方法。
import com.google.common.base.MoreObjects; public class MoreObjectsDemo { private String name; private String userId; private String petName; private String sex; @Override public String toString() { //prints:MoreObjectsDemo{name=testName, userId=NO1, petName=PIG} return MoreObjects.toStringHelper(this).add("name", "testName").add("userId", "NO1").add("petName", "PIG").omitNullValues().toString(); //prints:MoreObjectsDemo{name=testName, userId=NO1, petName=PIG} //return MoreObjects.toStringHelper(this).add("name", "testName").add("userId", "NO1").add("petName", "PIG").toString(); } public static void main(String[] args) { System.out.println(new MoreObjectsDemo()); } }
3、Stopwatch(计时器)
我们经常需要判断某一段语句执行需要多少时间,过去常用的做法是记录运行前的时间,然后用运行完成的时间减去运行前的时间,并且转换成我们可读的秒或是毫秒时间(这个转换过程可并不简单),在guava中可以有一个更好的方法:
import com.google.common.base.Stopwatch; public class StopWatchDemo { public static void main(String[] args) { final Stopwatch stopwatch = Stopwatch.createUnstarted().start(); //start stopwatch.start(); try { System.out.println("You can do something!"); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stopwatch.stop(); long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS); System.out.println(nanos);//1000076976 } }
附:TimeUUnit可选值有:
NANOSECONDS 毫微秒 十亿分之一秒(就是微秒/1000)
MICROSECONDS 微秒 一百万分之一秒(就是毫秒/1000)
MILLISECONDS 毫秒 千分之一秒
SECONDS 秒
MINUTES 分钟
HOURS 小时
DAYS 天
4、CharMatcher
字符匹配的方法特别多,举一个例子过滤用户的输出。
import com.google.common.base.CharMatcher; public class CharMatcherDemo { private static final CharMatcher ID_MATCHER = CharMatcher.DIGIT.or(CharMatcher.is('-')); public static void main(String[] args) { String userID = "123454-333"; String s = ID_MATCHER.retainFrom(userID); System.out.println(s);//123454-333 s = ID_MATCHER.retainFrom("1 test 11-222"); System.out.println(s);//可以把输入的的字符类型去掉,111-222 } }
5、String Joining 字符串连接
可以快速地把一组字符数组连接成为用特殊符合连接的一个字符串,如果这组字符中有null值的话,我们可以使用skipNulls或是useForNull来控制我们要输出的内容。
//Joiner JOINER= Joiner.on(",").skipNulls(); Joiner JOINER= Joiner.on(",").useForNull("null"); String str = JOINER.join("hello","world",null,"qiyadeng"); //hello,world,null,qiyadeng
6、String Splitting字符串分割
有这样一组字符串”hello, ,qiyadeng,com,”我们用split(“,”)分割字符串,得到的结果是[“hello”,”“,”qiyaeng”,”com”],但是我们如果希望的是把空值去掉,还需要另外处理,使用guava的Splitter可以简单做到。使用指定的分隔符对字符串进行拆分,默认对空白符不做任何处理,并且不会静默的丢弃末尾分隔符,如果需要处理的话要显式调用trimResults(),omitEmptyStrings()。
public class SplitterDemo { public static void main(String[] args) { Iterable<String> split = Splitter.on(',').trimResults().omitEmptyStrings().split("foo, ,bar,quux,blue,"); for (String s : split) { System.out.print(s + "---");//foo---bar---quux---blue--- } System.out.println(); String[] split1 = "foo, ,bar,quux,blue,".split(","); for (String s : split1) { System.out.print(s + "---");//foo--- ---bar---quux---blue--- } } }
7、Guava的官方API参考文档:
http://google.github.io/guava/releases/snapshot/api/docs/
https://github.com/google/guava
相关文章推荐
- 解决在Google浏览器中只能通过应用商店安装插件的问题
- Django知识点
- Google Analytics:为链接点击设定事件追踪的方法
- win to go 给移动硬盘装双系统
- Go做复杂的单向链表
- TOJ 1163.Gone Fishing(经典题目)
- five tips for good git commit
- Django1.9开发博客(7)- 实现功能
- django-ckeditor upload image and settings 完全解决方案。实践出真知
- POJ 3646 The Dragon of Loowater
- LeetCode - 122. Best Time to Buy and Sell Stock II
- Windows 下R软件如何安装GO.db程序包
- go语言十大排序算法总结(下篇)
- POJ 1003 Hangover
- runtime结合category和block动态增加方法以及属性
- google离线切片加载要点
- poj1042 Gone Fishing
- 【GO之初体验】GO中面向对象的特点
- GDB十分钟教程(转载自Liigo老师)
- HDU 3221 Brute-force Algorithm(指数降幂公式)