-2

I have the list of strings

List<String> lst;

I need to transform that list into a string as follows:

List<String> lst = new ArrayList<String>();
lst.add("String 1");
lst.add("String 2");
lst.add("String 3");

The String I want to get is:

"String 1 + String 2 + String 3"

If

List<String> lst = new ArrayList<String>();
lst.add("String 1");

then I just want String 1

If lst.isEmpty() then I want "".

Is it possible to do that in a flexible way and avoid writing multiple if-else if?

UPD: I'm on Java 7

St.Antario
  • 26,175
  • 41
  • 130
  • 318

2 Answers2

2

Assuming that you only want to use native Java (and don't want to use a third-party library like Apache), and desire 1.7, I don't really see a way around a simple for loop with an easy condition.

I'm not sure if this is "multiple if-else-if, but this seems fairly straight-forward:

List<String> lst = new ArrayList<String>();
lst.add("String 1");
lst.add("String 2");
lst.add("String 3");

StringBuilder output = new StringBuilder();
int size = lst.size();
for (int i = 0; i < size; i++) {
    output.append(lst.get(i));
    if (i < size - 1)
        output.append(" + ");
}

System.out.println(output.toString());

Hope this helps.

Ori Lentz
  • 3,668
  • 6
  • 22
  • 28
  • 2
    It's better to use [`StringBuilder`](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) instead of `+` operator. You'll note the difference when your list gets bigger. – Maroun May 20 '15 at 07:38
  • I agree with @MarounMaroun. – Raúl May 20 '15 at 07:38
  • Yeah, you're right. Thanks :) I've edit my answer to use `StringBuilder` – Ori Lentz May 20 '15 at 07:41
  • @OriLentz last note, the compile will optimize `lst.size()` in the loop body, don't worry about it. Moving it outside won't improve performance. – Maroun May 20 '15 at 07:43
2

Will it do ?

public static void main(String[] args) {

    ArrayList<String> list = new ArrayList<String>();
    list.add("String 1");
    list.add("String 2");
    list.add("String 3");

    StringBuilder convert = new StringBuilder();
    convert.append(list.isEmpty() ? "" : list.get(0));

    for(int i = 1 ; i < list.size() ; i ++ ) {
        convert.append(" + ").append(list.get(i)));
    }

    System.out.println(convert.toString());
}
Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42
  • 1
    Again, advise for [`StringBuilder`](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) instead of `+`. – Maroun May 20 '15 at 07:39
  • `convert.append(" + " + list.get(i))` this + should also be replaced by the StringBuilder functions And `&& list.size() >= 1` is unnecessary. – findusl May 20 '15 at 07:42