Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to join strings, each with a specific surrounding string?

Tags:

java

string

guava

I'm looking to use guava's Joiner to join List<String> into one string, but with surrounding strings around each one in the list. So I want to take a list of Strings:

List<String> names = Arrays.asList("John", "Mary", "Henry");

and generate this one string:

"your guest John is here, your guest Mary is here, your guest Henry is here"

The examples I see of using Joiner seem to be to generate the 3 names separated by a comma, but I'm looking to surround each string with some extra strings (the same ones every time).

I hope I'm being clear enough here. Thanks for your help.

like image 349
Steven Avatar asked Nov 25 '13 21:11

Steven


2 Answers

The way to do this is with a transform, first:

 Joiner.on(", ").join(Iterables.transform(names, new Function<String, String>() {
   public String apply(String str) { return "your guest " + str + " is here"; }
 }));
like image 52
Louis Wasserman Avatar answered Sep 29 '22 09:09

Louis Wasserman


How about

    String str = "your guest " + Joiner.on(" is here, your guest ").join(names) + " is here";
like image 25
Rhand Avatar answered Sep 29 '22 09:09

Rhand