Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
guava joiner examples
@Test
public void testJoiner() throws Exception {
List<String> texts = Lists.newArrayList("eins", null, "drei", "vier", "fünf", "sechs", "sieben", null);
String joined;
String expected;
joined = Joiner.on(";")
.skipNulls()
.join(texts);
expected = "eins;drei;vier;fünf;sechs;sieben";
assertThat(joined, is(expected));
joined = Joiner.on(";")
.useForNull("MISSING")
.join(texts);
expected = "eins;MISSING;drei;vier;fünf;sechs;sieben;MISSING";
assertThat(joined, is(expected));
}
@Test
public void testJoinerWithClassesThatImplementAppendeableInterface() throws Exception {
List<String> texts = Lists.newArrayList("1000200030004", "Apple", "MacBook Pro", null, "false");
File file = File.createTempFile("guava","study");
FileWriter fileWriter = new FileWriter(file);
Joiner.on(";")
.useForNull("N/A")
.appendTo(fileWriter, texts);
fileWriter.close();
FileReader fileReader = new FileReader(file);
BufferedReader reader = new BufferedReader(fileReader);
String csvLine = reader.readLine();
reader.close();
String expected = "1000200030004;Apple;MacBook Pro;N/A;false";
assertThat(csvLine, is(expected));
file.delete();
}
@Test
public void testJoinerWithStringBuilder() throws Exception {
List<String> texts = Lists.newArrayList("Never", "change", "a", null, "system");
StringBuilder sb = new StringBuilder();
Joiner.on(" ")
.useForNull("__________")
.appendTo(sb, texts);
String expected = "Never change a __________ system";
assertThat(sb.toString(), is(expected));
}
@Test
public void testMapJoiner() throws Exception {
Map<String,String> map = Maps.newLinkedHashMap();
map.put("Audi", "Neckarsulm");
map.put("VW", "Wolfsburg");
map.put("Merzedes", "Stuttgart");
map.put("Porsche", "Stuttgart");
map.put("Opel", "Rüsselsheim");
map.put("Ford", "Köln");
String joined = Joiner.on("#").withKeyValueSeparator("=").join(map);
String expected = "Audi=Neckarsulm#VW=Wolfsburg#Merzedes=Stuttgart#Porsche=Stuttgart#Opel=Rüsselsheim#Ford=Köln";
assertThat(joined, is(expected));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment