-1

This is a simple java coding question. I have a List of String [Say "hello" "how" "are" "you?"]. I need to insert a delimiter [-] between each element of the list so that my output is hello-how-are-you?

One simple way of doing this is as below:

private static String addDelim(List<String> a)
{
    String s = "";
    for(int i=0; i<a.size(); i++)
    {
        if(i != 0) // don't add if first element
        {
            s += "-";
        }

        s += a.get(i);
    }
    return s;
}

Is there any elegant way of doing this?

G.S
  • 10,413
  • 7
  • 36
  • 52
  • 1
    http://stackoverflow.com/a/187720/961113 – Habib Oct 07 '13 at 14:56
  • You can use a third-party library, such as Apache Commons, which contain utility methods for this kind of task. However, I doubt it has any code different from what you wrote. Maybe you could use `StringBuilder` for performance if your list has a lot of elements. – Mauren Oct 07 '13 at 14:58

4 Answers4

5

If you can include Guava (highly recommended), then the solution would be:

 return Joiner.on("-").join(s);
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Luke Usherwood
  • 3,082
  • 1
  • 28
  • 35
2

From Apache Commons Lang:

String out = StringUtils.join(yourList, '-');
sp00m
  • 47,968
  • 31
  • 142
  • 252
1

If you don't want to use external libraries, you better use StringBuilder:

private static String addDelim(List<String> a) {
    StringBuilder sb = new StringBuilder();
    for(int i=0; i < a.size(); i++) {
        if(i != 0) 
            sb.append("-");
        sb.append(a.get(i));
    }
    return sb.toString();
}
Maroun
  • 94,125
  • 30
  • 188
  • 241
1
StringBuilder sb = new StringBuilder();
for(String str: a){
    sb.append(str).append('-');
}
sb.deleteCharAt(sb.length() -1);