Guava의 Joiner와 Splitter 중 잘 사용 중인 부분이다.
import java.util.List;
import org.junit.Test;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
public class JoinAndSplitTest {
@Test
public void JoinerTest() {
System.out.println("== joiner demo ==");
Joiner joiner = Joiner.on(", ").skipNulls();
String names = joiner.join("Samuel", null, "Aston", "Kalley");
System.out.println("names : " + names);
Joiner joinerUsingNull = Joiner.on(", ").useForNull("N/A");
String namesUsingNull = joinerUsingNull.join("Samuel", null, "Aston", "Kalley");
System.out.println("names using null : " + namesUsingNull);
List<String> list = Lists.newArrayList("1", "2", "3");
String string = Joiner.on(",").join(list);
System.out.println("list : " + string);
}
@Test
public void SplitterTest() {
System.out.println("== splitter demo ==");
Iterable<String> listByComma = Splitter.on(',')
.trimResults()
//.omitEmptyStrings()
.split("aston,samuel,,jason");
System.out.println("* test1");
for (String string : listByComma) {
System.out.println(string);
}
Iterable<String> listByTab = Splitter.on('\t')
.trimResults()
.omitEmptyStrings()
.split("aston samuel jason");
System.out.println("* test2");
for (String string : listByTab) {
System.out.println(string);
}
Iterable<String> listByTabAndSpace = Splitter.on('\t')
.trimResults()
.omitEmptyStrings()
.split("aston samuel jason");
System.out.println("* test3");
for (String string : listByTabAndSpace) {
System.out.println(string);
}
}
}
결과
== joiner demo ==
names : Samuel, Aston, Kalley
names using null : Samuel, N/A, Aston, Kalley
list : 1,2,3
== splitter demo ==
* test1
aston
samuel
jason
* test2
aston
samuel
jason
* test3
aston
samuel
jason
이 것 말고, http request parameter를 만들 때처럼 joiner를 활용할 수 있다.
예제
public void mapJoinTest() {
Map<String, String> map =
ImmutableMap.<String, String>builder()
.put("name", "Samuel")
.put("phone", "111")
.put("address", "Sanfrancisco")
.build();
String joined = Joiner.on("&").withKeyValueSeparator("=").join(map);
System.out.println("http://localhost/join.api?" + joined);
결과
http://localhost/join.api?name=Samuel&phone=111&address=Sanfrancisco
'general java' 카테고리의 다른 글
[Guava] ImmutableMap, ImmutableSet, ImmutableList 예제 (0) | 2015.04.10 |
---|---|
[Guava] Iterables.transform 과 removeIf 예제 (0) | 2015.04.10 |
[Guava] 자주 사용하는 Maps api (0) | 2015.04.09 |
[Guava] 자주 사용하는 Sets api (0) | 2015.04.09 |
[Guava] comparator를 여러 번 이용해서 Object 소팅하기 (0) | 2015.04.08 |