@GwtCompatible public class Joiner extends Object
An object which joins pieces of text (specified as an array,
Iterable
, varargs or even a Map
) with a separator. It either appends the results to an Appendable
or returns them as a String
./**Please follow my comments in the code to relate with the output
*
*/
package com.rajkrrsingh.test.guava;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Functions;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2;
import com.google.common.collect.Iterables;
/**
* @author rks
* @04-Jan-2015
*/
public class GuavaJoinerDemo {
public static void main(String[] args) {
joinerDemo();
}
// tranform a collection into a sting
public static void joinerDemo(){
List<String> list = Arrays.asList("RKS","John","Nick","Harry");
System.out.println(Joiner.on("#").join(list));
List<String> list1 = Arrays.asList("RKS","John",null,"Nick","Harry");
//skip nulls
System.out.println(Joiner.on("#").skipNulls().join(list1));
//defualt value for null
System.out.println(Joiner.on("#").useForNull("BLANK").join(list1));
// joiner on Map
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
map.put("key4", "value4");
System.out.println(Joiner.on("#").withKeyValueSeparator(":").join(map));
}
}
RKS#John#Nick#Harry RKS#John#Nick#Harry RKS#John#BLANK#Nick#Harry key4:value4#key3:value3#key2:value2#key1:value1
No comments:
Post a Comment