I have requirement in Joiner to have the ability to prefix and suffix elements.
For example
String str[] = {"a", "b", "c"};
Joiner.on(",").prefix("'").suffix("'").join(str);
Expected output would be:
'a','b','c'
Do we have any alternative for this? As Guava doesn't do it (or I'm not aware of). With java 8 is there a better alternative?
String str = "Hello world. welcome world java."; String[] wordArr = str. split("[. ]"); Set<String> words = new HashSet<>(Arrays. asList(wordArr)); for (String w: words) { if(w.
A prefix of a string S is a substring of S that occurs at the beginning of S. A suffix of a string S is a substring that occurs at the end of S. Output the size of the largest such subset.
The most idiomatic way to do this in modern Java is String. format("%s%d", s, i); where s is a String and i is an int . It partly depends on whether you want locale-sensitive output. This will use a locale-sensitive formatter; text + integer won't.
You can use Guava's List#transform
to make the transformation a --> 'a'
and then use Joiner
on the transformed list. transform
only works on Iterable
objects, though, not on arrays. The code will still be succinct enough:
List<String> strList = Lists.newArraylist(str); // where str is your String[]
Joiner.on(',').join(Lists.transform(str, surroundWithSingleQuotes));
where the transformation is as follows:
Function<String, String> surroundWithSingleQuotes = new Function<String, String>() {
public String apply(String string) {
return "'" + string + "'";
}
};
One might say this is a long-winded way of doing this, but I admire the amount of flexibility provided by the transform
paradigm.
Edit (because now there's Java 8)
In Java 8, all this can be done in a single line using the Stream interface, as follows:
strList.stream().map(s -> "'" + s + "'").collect(Collectors.joining(","));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With