Why StringJoiner when we already have StringBuilder?

后端 未结 5 1707
渐次进展
渐次进展 2020-12-01 04:30

I recently encountered with a Java 8 class StringJoiner which adds the String using the delimiters and adds prefix and suffix to it, but I can\'t understand the need of this

5条回答
  •  一个人的身影
    2020-12-01 04:51

    The examples on the StringJoiner Javadoc are very good at covering this. The whole point to to abstract away the choice of seperator from the act of adding entries. e.g. you can create a joiner, specify the seperator to use and pass it to a library to do the adding of elements or visa versa.

    The String "[George:Sally:Fred]" may be constructed as follows:

    StringJoiner sj = new StringJoiner(":", "[", "]");
    sj.add("George").add("Sally").add("Fred");
    String desiredString = sj.toString();
    

    A StringJoiner may be employed to create formatted output from a Stream using Collectors.joining(CharSequence). For example:

    List numbers = Arrays.asList(1, 2, 3, 4);
    String commaSeparatedNumbers = numbers.stream()
        .map(i -> i.toString())
        .collect(Collectors.joining(", "));
    

提交回复
热议问题