Sunday, February 17, 2013

Guava - Strings - Joiner

"Joining together a sequence of strings with a separator can be unnecessarily tricky..." [1]
Java 
String[] array = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};    
String separator = "||";

StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < (array.length - 1); i++) {
  stringBuilder.append(array[i]);
  stringBuilder.append(separator);
}
stringBuilder.append(array[array.length - 1]);
Unless I'm missing something, I wouldn't necessarily call that tricky.  The only "tricky" part is stopping one element before the last so that you don't have to remove the extra trailing separator.
Guava
String[] array = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};    
String separator = "||";

Joiner.on(separator).join(array);
That's definitely a lot shorter and easier to read.  I know this is splitting hairs, but I wish the syntax was different.  I'd rather type "Joiner.join(array).on(separator)" or "Joiner.join(array).with(separator);"
"If your sequence contains nulls, it can be even harder." [1]
Java 
String[] array = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};    

// Make every other element null.

// array[0];      // "The" 
array[1] = null;  // "quick"
// array[2];      // "brown" 
array[3] = null;  // "fox"
// array[4];      // "jumps"
array[5] = null;  // "over" 
// array[6];      // "the" 
array[7] = null;  // "lazy", 
// array[8];      // "dog"

String separator = "||";

StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < array.length; i++) {
  if(null != array[i]) {
    stringBuilder.append(array[i]);
    stringBuilder.append(separator);         
  }
}

stringBuilder.substring(0, stringBuilder.lastIndexOf(separator));
The tricky part this time was removing the trailing separator.
Guava
String[] array = {"The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};    

// Make every other element null.

// array[0];      // "The" 
array[1] = null;  // "quick"
// array[2];      // "brown" 
array[3] = null;  // "fox"
// array[4];      // "jumps"
array[5] = null;  // "over" 
// array[6];      // "the" 
array[7] = null;  // "lazy", 
// array[8];      // "dog"

String separator = "||";

Joiner.on(separator).skipNulls().join(array);
It's also easy to specify a substitute value for nulls in Guava.
Joiner.on(separator).useForNull("null").join(array);
It should be noted that Joiner instances are immutable (which means that they are also thread-safe). [1]  So every other element in the above array is still null and not the String "null".

References

[1] Guava's wiki page for StringsExplained 

No comments:

Post a Comment