public String buildString(List<String> stringList, String delimiter){ StringBuilder builder = new StringBuilder(); for (String s : stringList) { if(s !=null){ builder.append(s).append(delimiter); } } builder.setLength(builder.length() – delimiter.length()); return builder.toString(); }
public String buildString(List<String> stringList, String delimiter){ return Joiner.on(delimiter).skipNulls().join(stringList); }
Joiner.on("|").useForNull("no value").join(stringList);
Joiner stringJoiner = Joiner.on("|").skipNulls(); //使用useForNull方法将会返回一个新的Joiner实例 stringJoiner.useForNull("missing"); stringJoiner.join("foo","bar",null);
StringBuilder stringBuilder = new StringBuilder(); Joiner joiner = Joiner.on("|").skipNulls(); //返回的StringBuilder实例当中包含连接完成的字符串 joiner.appendTo(stringBuilder,"foo","bar","baz");
FileWriter fileWriter = new FileWriter(new File("path")): List<Date> dateList = getDates(); Joiner joiner = Joiner.on("#").useForNulls(" "); // 返回由字符串拼接后的FileWriter实例 joiner.appendTo(fileWriter,dateList);
MapJoiner mapJoiner = Joiner.on("#").withKeyValueSeparator("=");
@Test public void testMapJoiner() { String expectedString = "Washington D.C=Redskins#New York City=Giants#Philadelphia=Eagles#Dallas=Cowboys"; 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); assertThat(returnedString,is(expectedString)); }
String testString = "Monday,Tuesday,,Thursday,Friday,,"; //parts is [Monday, Tuesday, , Thursday,Friday] String[] parts = testString.split(",");
Splitter.on('|').split("foo|bar|baz");
Splitter splitter = Splitter.on("\\d+");
//Splits on '|' and removes any leading or trailing whitespace Splitter splitter = Splitter.on('|').trimResults();
Splitter splitter = Splitter.on('|'); //Next call returns a new instance, does not modify the original! splitter.trimResults(); //Result would still contain empty elements Iterable<String> parts = splitter.split("1|2|3|||");
//MapSplitter is defined as an inner class of Splitter Splitter.MapSplitter mapSplitter = Splitter.on("#"). withKeyValueSeparator("=");
@Test public void testSplitter() { String startString = "Washington D.C=Redskins#New York City=Giants#Philadelphia=Eagles#Dallas=Cowboys"; 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"); Splitter.MapSplitter mapSplitter = Splitter.on("#").withKeyValueSeparator("="); Map<String,String> splitMap = mapSplitter.split(startSring); assertThat(testMap,is(splitMap)); }
byte[] bytes = someString.getBytes();
try{ bytes = "foobarbaz".getBytes("UTF-8"); }catch (UnsupportedEncodingException e){ //This really can't happen UTF-8 must be supported }
byte[] bytes2 = "foobarbaz".getBytes(Charsets.UTF_8);
StringBuilder builder = new StringBuilder("foo"); char c = 'x'; for(int i=0; i<3; i++){ builder.append(c); } return builder.toString();
Strings.padEnd("foo",6,'x');
CharMatcher.BREAKING_WHITESPACE.replaceFrom(stringWithLinebreaks,' ');
@Test public void testRemoveWhiteSpace(){ String tabsAndSpaces = "String with spaces and tabs"; String expected = "String with spaces and tabs"; String scrubbed = CharMatcher.WHITESPACE.collapseFrom(tabsAndSpaces,' '); assertThat(scrubbed,is(expected)); }
@Test public void testTrimRemoveWhiteSpace(){ String tabsAndSpaces = " String with spaces and tabs"; String expected = "String with spaces and tabs"; String scrubbed = CharMatcher.WHITESPACE. trimAndCollapseFrom(tabsAndSpaces,' '); assertThat(scrubbed,is(expected)); }
@Test public void retainFromTest() { String lettersAndNumbers = "foo989yxbar234"; String expected = "989234"; String actual = CharMatcher.JAVA_DIGIT.retainFrom(lettersAndNumbers); assertEquals(expected, actual); }
CharMatcher cm = CharMatcher.JAVA_DIGIT.or(CharMatcher.WHITESPACE);
if(someObj == null){ throw new IllegalArgumentException(" someObj must not be null"); }
checkNotNull(someObj,"someObj must not be null");
public class PreconditionExample { private String label; private int[] values = new int[5]; private int currentIndex; public PreconditionExample(String label) { //返回label如果不为空 this.label = checkNotNull(label,"Label can''t be null"); } public void updateCurrentIndexValue(int index, int valueToSet) { //检查索引是否有效 this.currentIndex = checkElementIndex(index, values.length, "Index out of bounds for values"); //检查参数值 checkArgument(valueToSet <= 100,"Value can't be more than 100"); values[this.currentIndex] = valueToSet; } public void doOperation(){ checkState(validateObjectState(),"Can't perform operation"); } private boolean validateObjectState(){ return this.label.equalsIgnoreCase("open") && values[this. currentIndex]==10; } }
public class Book implements Comparable<Book> { private Person author; private String title; private String publisher; private String isbn; private double price; public String toString() { return Objects.toStringHelper(this).omitNullValues().add("title", title).add("author", author).add("publisher", publisher) .add("price",price).add("isbn", isbn).toString(); } }
String value = Objects.firstNonNull(someString, "default value");
public int hashCode() { return Objects.hashCode(title, author, publisher, isbn); }
public int compareTo(Book o) { int result = this.title.compareTo(o.getTitle()); if (result != 0) { return result; } result = this.author.compareTo(o.getAuthor()); if (result != 0) { return result; } result = this.publisher.compareTo(o.getPublisher()); if(result !=0 ) { return result; } return this.isbn.compareTo(o.getIsbn()); }
public int compareTo(Book o) { return ComparisonChain.start() .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(); }