问题描述
我最近遇到了一个 Java 8 类 StringJoiner
它使用分隔符添加字符串并为其添加前缀和后缀,但我无法理解此类的需要,因为它也使用 StringBuilder
在后端,也执行非常简单的追加操作字符串.
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 class as it also uses StringBuilder
at the backend and also performs very simple operation of appending the Strings.
我是否因为没有真正理解这门课的真正目的而错过了什么?
Am I missing something by not actually understanding the real purpose of this class?
推荐答案
StringJoiner
非常有用,当你需要在 Stream
中加入 Strings 时.
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<String> strings = Arrays.asList("Foo", "Bar", "Baz");
使用起来更简单
final String collectJoin = strings.stream().collect(Collectors.joining(", "));
就像使用 StringBuilder
一样:
final String collectBuilder =
strings.stream().collect(Collector.of(StringBuilder::new,
(stringBuilder, str) -> stringBuilder.append(str).append(", "),
StringBuilder::append,
StringBuilder::toString));
6 年后编辑正如评论中所指出的,现在有更简单的解决方案,例如 String.join(", ", strings)
,当时还没有这些解决方案.但是用例还是一样的.
EDIT 6 years laterAs 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.
这篇关于当我们已经有了 StringBuilder 时,为什么要使用 StringJoiner?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!