Kima321
Kima321

Reputation: 55

Combining strings without using plus '+'

I am writing unit tests now and I need to create a specific string.

I have now defined something like this:

private final String at = "@:";
private String error, effect, one, two, three, four;

in setUp (@Before):

    error = RandomStringUtils.randomAlphabetic (3);
    one = RandomStringUtils.randomAlphabetic (6);
    two = RandomStringUtils.randomAlphabetic (8);
    three = RandomStringUtils.randomAlphabetic (2);
    four = RandomStringUtils.randomAlphabetic (6);
    effect = (error + at + one + at + two + at + three + at + four);

The combination of the strings with the pluses looks terribly ugly and amateurish. Is it possible to do it somehow more efficiently using anything else? For example pattern? I dont know. Thanks for help :)

Upvotes: 1

Views: 379

Answers (3)

DaveyDaveDave
DaveyDaveDave

Reputation: 10562

If the "@:" is a consistent separator, and you're using Java 8+, you might find that String.join is your friend. This would look something like:

effect = String.join("@:", error, one, two, three, four);

Guessing a little bit from your variable names, but as a little background and just in case it's helpful, if you want/need to use a Stream you can also use Collectors.joining, which could look something like:

List<String> stringParts = ...
stringParts.stream()
  .collect(Collectors.joining("@:"));

This will join everything in the list with "@:" as a delimiter. You can also add a constant prefix and/or suffix which might be relevant for your error variable, like:

String error = RandomStringUtils.randomAlphabetic(3);
List<String> stringParts = ...
stringParts.stream()
  .collect(Collectors.joining("@:", error, ""));

Upvotes: 5

Rob Audenaerde
Rob Audenaerde

Reputation: 20019

You can use the java built-in StringBuilder

StringBuilder sb = new StringBuilder();
sb.append(error);
sb.append(at);
sb.append(one);
...
effect = sb.toString();

Upvotes: 7

Niels Bech Nielsen
Niels Bech Nielsen

Reputation: 4859

For simplicity, you can also do:

String.join(at, error,one, two, three, four);

Upvotes: 10

Related Questions