Guava의 Joiner와 Splitter 중 잘 사용 중인 부분이다. 



package com.google;


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를 활용할 수 있다. 


예제

@Test
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



Posted by '김용환'

댓글을 달아 주세요