本篇主要给出Guava基础部分的一些实例:Joiner,Splitters,Strings,Preconditions,Objects,MoreObjects中一些方法的使用,具体的请参考Guava api或源码。
Joiner 主要是集合的一些拼接操作:
public class JoinerDemo { List<String> stringList=new ArrayList<String>(); @Before public void init(){ stringList.add("a"); stringList.add("b"); stringList.add("c"); stringList.add(null); } //默认情况,遇到null,抛exception @Test public void defaultJoin(){ String strDefault = Joiner.on("|").join(stringList); System.out.println(strDefault); } @Test public void skipNull(){ //忽略null String str= Joiner.on("|").skipNulls().join(stringList); System.out.println(str); } @Test public void useForNull(){ //不忽略null String str2=Joiner.on("|").useForNull("no value").join(stringList); System.out.println(str2); } //joiner 可以使用实现Appendable接口的类 @Test public void join() throws Exception{ FileWriter fileWriter = new FileWriter("D://log//haha.txt"); Joiner joiner=Joiner.on("#").useForNull(" "); joiner.appendTo(fileWriter,stringList); fileWriter.close(); } //用于对map进行连接 @Test public void testMapJoiner(){ Map<String,String> testMap= Maps.newLinkedHashMap(); testMap.put("Washington D.C","Redskins"); testMap.put("New York City","Giants"); testMap.put("Philadelphia","Eagles"); testMap.put("Dallas","Cowboys"); String returnedString=Joiner.on("#").withKeyValueSeparator("=").join(testMap); System.out.println(returnedString); } }
public class SplitterDemo { /** * a common task for programmers is to take a string with some delimiter character * and plit that string on the delimiter and obtain an array of the parts of the string */ @Test public void common(){ String testString="Monday,Tuesday,Thursday,Friday,,"; Iterable<String> parts=Splitter.on(",").split(testString); for(String s:parts) System.out.println(s); } /** * Splitter.trimResults 去掉结果集Iterable每个元素的首尾的空格 */ @Test public void trimResults(){ //Just like the Joiner class,Splitter is immutable on creation, //so care must be taken to not call the trimResults method after //creating the original Splitter class Splitter splitter=Splitter.on("|").trimResults(); Iterable<String> parts=splitter.split("1| 2 | 3 ||"); for(String s:parts) System.out.println(s); } /** * 将指定格式的字符串分割成map */ @Test public void testSplitToMap(){ String testString="Washington D.C=Redskins#New York City=Giants#Philadelphia=Eagles#Dallas=Cowboys"; Splitter.MapSplitter mapSplitter=Splitter.on("#").withKeyValueSeparator("="); Map<String,String> testMap=mapSplitter.split(testString); for(String key:testMap.keySet()) System.out.println(testMap.get(key)); } }
Charsets 主要是一些常见的编码
CharMatcher 主要是一些简单的正则
public class StringsDemo { /** * Charsets */ public void testCharsets(){ byte[] bytes="haha".getBytes(Charsets.UTF_8); } /** * Strings static String nullToEmpty(String string) 如果string为null,则返回"" static String emptyToNull(String string) 如果string为"",返回null static boolean isNullOrEmpty(String string) 判断string是否为null或长度是否为0 static String commonPrefix(CharSequence a, CharSequence b) 返回a,b共同的最长前缀 static String commonSuffix(CharSequence a, CharSequence b) 返回a,b共同的最长后缀 static String padEnd(String string, int minLength, char padChar) 使用padChar在尾部将string填充到指定长度minLength static String padStart(String string, int minLength, char padChar) 使用padChar在头部将string填充到指定长度minLength static String repeat(String string, int count) 将字符串重复N次,返回新字符串 */ @Test public void testStrings(){ String res=Strings.padEnd("start",10,'a'); System.out.println(res); res=Strings.repeat("hello",5); System.out.println(res); } @Test public void testCharMatcher(){ //换行使用空格替换 // CharMatcher.BREAKING_WHITESPACE.replaceFrom(strinfWithlineBreaks," "); //多个空字符使用' ' 替换 String tabsAndSpaces="String with spaces and tabs"; String scrubbed=CharMatcher.WHITESPACE.collapseFrom(tabsAndSpaces,' '); System.out.println(scrubbed); //去掉首尾空字符,多个空字符使用' ' 替换 String tabsAndSpaces2=" String with spaces and tabs"; scrubbed=CharMatcher.WHITESPACE.trimAndCollapseFrom(tabsAndSpaces2,' '); System.out.println(scrubbed); //只保留数字 String lettersAndNumbers="foo988yxbar12323"; String retained=CharMatcher.JAVA_DIGIT.retainFrom(lettersAndNumbers); System.out.println(retained); //匹配多个模式 String lettersAndOthers="foo988xasfas dfasd123"; CharMatcher cm=CharMatcher.JAVA_DIGIT.or(CharMatcher.WHITESPACE); retained=cm.retainFrom(lettersAndOthers); System.out.println(retained); } }
public class User implements Comparable<User>{ private Integer id; private String name; private String address; public String toString(){ return MoreObjects.toStringHelper(this).add("id",id).add("name",name).add("address",address).toString(); } public int hashCode(){ return Objects.hashCode(id,name,address); } @Override public int compareTo(User o) { return ComparisonChain.start().compare(this.id,o.id).compare(this.name,o.name).compare(this.address,o.address).result(); } }
参考资料:《Getting started with Google Guava》