This is the 12th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Actual combat tips 4: elegant implementation string concatenation

A daily practical tip, string concatenation

Believe that no partner has not written such code, such as now let’s implement a string concatenation of the scene, what is the implementation of elegant?

Take the example of converting an int array into a comma-delimited string

1. Ordinary writing

Use StringBuilder directly to concatenate

public String join(List<Integer> list) {
    StringBuilder builder = new StringBuilder();
    for(Integer sub: list) {
        builder.append(sub).append(",");
    }
    return builder.substring(0, builder.length() - 1);
}
Copy the code

The more common, less pleasing part is the last toString, where the last comma needs to be removed

Of course, you can avoid the final string truncation by using the following pre-judgment method

public String join2(List<Integer> list) {
    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for (Integer sub: list) {
        if (first) {
            first = false;
        } else {
            builder.append(",");
        }
        builder.append(sub);
    }
    return builder.toString();
}
Copy the code

2. StringJoiner

In the above implementation, killing the last delimiter is not very elegant. Is there a better way to use it? Let’s look at how to use StringJoiner

public String join3(List<Integer> list) {
    StringJoiner joiner = new StringJoiner(",");
    for (Integer s : list) {
        joiner.add(String.valueOf(s));
    }
    return joiner.toString();
}
Copy the code

StringJoiner is provided by JDK1.8. In addition to the above basic gameplay, the StringJoiner can be implemented more succinct with the flow operation mode brought by JDK1.8

return list.stream().map(String::valueOf).collect(Collectors.joining(","));
Copy the code

So, is this implementation much cleaner than the previous code, one line of code

3. guava joiner

If you are not using JDK 1.8, you cannot use StringJoiner, but you can also implement Guava’s Joiner

public String join5(List<Integer> list) {
    return Joiner.on(",").join(list);
}
Copy the code

Pay attention to

  • The received parameters are of type: array /Iterable/Iterator/ variator, which basically covers our everyday business scenarios

4. Summary

The topic of this article is a very, very common string concatenation. In general, when we do string concatenation, the most troublesome thing is to handle the delimiter. Or it’s postset, and when you get to the last string, it kills the last delimiter

This article provides a common StringJoiner approach that completely solves the above delimiter problem and can be used in two scenarios

  • Simple container to String: directly with StreamCollectors.joiningTo implement the
  • For loops (typically in this scenario where the logic inside a for loop includes more than string concatenation, but also other business logic) : executes directly within the loopstringJoiner.add()add

For jdk1.8 and above, it is preferred to use StringJoiner as described above. Under JDK1.8, Guava is a good choice, and it’s easy to use

Series of blog posts

  • Practical tips 1: string placeholder replacement -JDK version
  • Practical tips 2: Array and list inter-transfer
  • Practical tip 3: String and container interchange

II. The other

1. A gray Blog:liuyueyi.github.io/hexblog

A gray personal blog, record all study and work in the blog, welcome everyone to visit

2. Statement

The above content is not as good as the letter, purely the words of a family, due to the limited personal ability, there are inevitably omissions and mistakes, such as found bugs or better suggestions, welcome criticism and correction, not grudging gratitude

  • Micro-blog address: small gray Blog
  • QQ: A gray /3302797840
  • Wechat official account: a gray blog