Skip to content

Instantly share code, notes, and snippets.

@dfparker2002
Forked from K0NRAD/JoinerTest.java
Created June 26, 2016 23:37
Show Gist options
  • Save dfparker2002/e16866bb12916f25bbb0786ba42028f8 to your computer and use it in GitHub Desktop.
Save dfparker2002/e16866bb12916f25bbb0786ba42028f8 to your computer and use it in GitHub Desktop.
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