Why StringJoiner when we already have StringBuilder?

后端 未结 5 1696
渐次进展
渐次进展 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:30

    StringJoiner is very useful, when you need to join Strings in a Stream.

    As an example, if you have to following List of Strings:

    final List strings = Arrays.asList("Foo", "Bar", "Baz");
    

    It is much more simpler to use

    final String collectJoin = strings.stream().collect(Collectors.joining(", "));
    

    as it would be with a StringBuilder:

    final String collectBuilder =
        strings.stream().collect(Collector.of(StringBuilder::new,
            (stringBuilder, str) -> stringBuilder.append(str).append(", "),
            StringBuilder::append,
            StringBuilder::toString));
    

    EDIT 6 years later As noted in the comments, there are now much simpler solutions like String.join(", ", strings), which were not available back then. But the use case is still the same.

提交回复
热议问题