Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Joiner doesn't have ability to prefix and suffix [duplicate]

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?

like image 704
Mohammad Adnan Avatar asked Jan 06 '14 08:01

Mohammad Adnan


People also ask

How do you add a prefix and suffix to a string in Java?

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.

What is prefix and suffix in Java?

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.

How do you add a suffix to a string in Java?

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.


1 Answers

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(","));
like image 173
Chthonic Project Avatar answered Oct 30 '22 07:10

Chthonic Project