-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

4
  • 2
    Joiner, or switch to Java 8, there are many options. Commented May 20, 2015 at 7:32
  • 1
    Didn't we solved this on SO already? Commented May 20, 2015 at 7:38
  • @MarounMaroun What would be a possible solution in Java 8? Commented May 20, 2015 at 7:39
  • @St.Antario it's explained in the dupe. Commented May 20, 2015 at 7:39

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It's better to use StringBuilder instead of + operator. You'll note the difference when your list gets bigger.
I agree with @MarounMaroun.
Yeah, you're right. Thanks :) I've edit my answer to use StringBuilder
@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.
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());
}

2 Comments

Again, advise for StringBuilder instead of +.
convert.append(" + " + list.get(i)) this + should also be replaced by the StringBuilder functions And && list.size() >= 1 is unnecessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.