guava 是google工程师开源的java工具包,里面包括了大量常用及好用的工具总结,谷歌的内部工程师也在大量使用。
guava主要包括这些包:
base
基本的工具类与接口
io
io流相关的工具类与方法
net
网络地址相关的工具类与方法
primitives 原始类型的工具类
collect
通用集合接口与实现,与其集合相关工具类
util.concurrent 并发相关工具类
字符串:
1
2
3
4
5
6 |
Splitter.on( ‘,‘ ).split( "a,b" ); Splitter.on( ‘,‘ ).trimResults().split( "a , b" ); Splitter.on( ‘,‘ ).omitEmptyStrings().split( "a,,b" ); Strings.isNullOrEmpty( "" ) Strings.repeat( "java" , 3 ) Assert.assertEquals( "2011-08-04" , Joiner.on( "-" ).join( "2011" , "08" , "04" )); |
链式操作:
String s = Joiner.on(“,”).skipNulls().join(new int[]{2,3,4});//将int数组拼成字符串 String s = Joiner.on(“;”).withKeyValueSeparator(“|”).join(userIdNameMap);//针对map的 CaseFormat : Assert.assertEquals("HELLO_GUAVA", CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "helloGuava")); Assert.assertEquals("HelloGuava", CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "hello-guava"));
文件操作:
Files.copy(from,to); Files.deleteDirectoryContents(File directory); //删除文件夹下的内容(包括文件与子文件夹) Files.deleteRecursively(File file); //删除文件或者文件夹 Files.move(File from, File to); //移动文件
Preconditions :
Preconditions.checkArgument(count > 0, "must be positive: %s", count); //判断 抛异常
Resources提供了针对classpath下资源操作的工具方法 :
URL url =
Resources.getResource("config.xml"); //获取classpath根下的config.xml文件url
Guava新增了一个概念,叫做 不可变集合,ImmutableCollection:
Map params = ImmutableMap.of(“name”, “zhangsan”, “age”, 20);
非常实用的一个API: MapDifference<K, V> diff = Maps.difference(Map<K, V>
left, Map<K, V> right); 之后可以调用
diff.entriesOnlyOnLeft() // 获得只在左集合有的部分
diff.entriesOnlyOnRight() // 获得只在右集合有的部分
diff.entriesInCommon() //
获得交集部分
Guava新增了一个概念,叫做BiMap,双向Map,比如说我需要一个Map,可以根据用户ID找到用户昵称,还可以根据用户昵称查找用户ID,这时就可以用到双向Map了。
原文:http://www.cnblogs.com/michael-geng/p/3655795.html