问题描述
我最近遇到过Java 8类使用分隔符添加String并添加前缀和后缀,但我无法理解这个类的需要,因为它也使用 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
非常有用,当你需要以<$ c $加入字符串时c> Stream 。
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));
这篇关于为什么我们已经有StringBuilder的StringJoiner?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!