0

Java 11 here. I am trying to use org.apache.commons.lang3.StringUtils.join to take a list of strings and join/concatenate them into a single string, separated by an @ sign. If there is only one (1) string in the list, then the joins/concatenated output should be that same string, no delimiter. Hence:

  • If inputList string is [ "Hello", "World" ], output should be "Hello@World"
  • If inputList string is [ "Hello" ], output should be "Hello"

My best attempt thus far is:

String output = StringUtils.join("@", inputList);

But for an inputList of [ "Hello", "World" ] this gives me output of:

@[Hello, World]

And for an inputList of [ "Hello" ], this gives me output of:

@[Hello]

Can anyone spot where I'm going awry?

simplezarg
  • 168
  • 1
  • 9
  • Of course, you don't need a third party library to do that: `String s = stringList.stream().collect(Collectors.joining("@"));` – g00se Mar 17 '23 at 14:31

2 Answers2

3

You are using wrong order of arguments. You will need to pass the array as a first argument and delimiter as the second argument.

Some sample examples outputs are like this:

StringUtils.join(null, *)                = null
StringUtils.join([], *)                  = ""
StringUtils.join([null], *)              = ""
StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
StringUtils.join(["a", "b", "c"], null)  = "abc"
StringUtils.join(["a", "b", "c"], "")    = "abc"
StringUtils.join([null, "", "a"], ',')   = ",,a"

The definition of join method is:

public static String join(final Object[] array, final String delimiter) {
    if (array == null) {
        return null;
    }
    return join(array, delimiter, 0, array.length);
}
Ankit Wasankar
  • 145
  • 1
  • 12
1

The method itself works, you just need to put in the array first, then the delimiter. In the documentation there is an example, and when I just tried it it worked.

The following code outputs Hello@World, I just switched the parameters.

    String[] inputList = new String[] { "Hello", "World" };
    String joined = StringUtils.join(inputList, "@");
    System.out.println(joined);
Raph
  • 26
  • 1
  • 2