Java 当我们已经有了 StringBuilder 时,为什么要使用 StringJoiner?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27522563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why StringJoiner when we already have StringBuilder?
提问by Hitesh Garg
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.
我最近遇到了一个 Java 8 类StringJoiner
,它使用分隔符添加字符串并为其添加前缀和后缀,但我无法理解这个类的需要,因为它也在StringBuilder
后端使用,并且还执行非常简单的附加操作字符串。
Am I missing something by not actually understanding the real purpose of this class?
我是否因为没有真正理解这门课的真正目的而错过了什么?
采纳答案by Martin Seeler
StringJoiner
is very useful, when you need to join Strings in a Stream
.
StringJoiner
非常有用,当您需要在Stream
.
As an example, if you have to following List of Strings:
例如,如果您必须遵循字符串列表:
final List<String> 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
:
就像这样StringBuilder
:
final String collectBuilder =
strings.stream().collect(Collector.of(StringBuilder::new,
(stringBuilder, str) -> stringBuilder.append(str).append(", "),
StringBuilder::append,
StringBuilder::toString));
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.
6 年后编辑如评论中所述,现在有更简单的解决方案,例如String.join(", ", strings)
,当时还没有。但用例仍然相同。
回答by Peter Lawrey
The examples on the StringJoiner Javadocare 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.
StringJoiner Javadoc上的示例非常擅长涵盖这一点。重点是从添加条目的行为中抽象出分隔符的选择。例如,您可以创建一个连接器,指定要使用的分隔符并将其传递给库以添加元素,反之亦然。
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<Integer> numbers = Arrays.asList(1, 2, 3, 4); String commaSeparatedNumbers = numbers.stream() .map(i -> i.toString()) .collect(Collectors.joining(", "));
字符串 "[George:Sally:Fred]" 可以构造如下:
StringJoiner sj = new StringJoiner(":", "[", "]"); sj.add("George").add("Sally").add("Fred"); String desiredString = sj.toString();
可以使用 StringJoiner 从使用 Collectors.joining(CharSequence) 的 Stream 创建格式化输出。例如:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4); String commaSeparatedNumbers = numbers.stream() .map(i -> i.toString()) .collect(Collectors.joining(", "));
回答by Konstantin Yovkov
StringJoiner
is a kind of a Collector, although it doesn't implement the Collector
interface. It just behaves as such. Besides you can pass delimiter, prefix and suffix, the StringJoiner
may be employed to create formatted output from a Stream
invoking Collectors.joining(CharSequence)
.
StringJoiner
是一种Collector,虽然它没有实现Collector
接口。它只是表现得如此。除了您可以传递分隔符、前缀和后缀之外,StringJoiner
还可用于从Stream
调用Collectors.joining(CharSequence)
.
This is especially useful when working with parallel streams, because at some point the batches that are being process in parallel will need to be joinedand this is where the StringJoiner
takes place.
这在处理并行流时特别有用,因为在某些时候,并行处理的批次需要连接,这就是StringJoiner
发生的地方。
回答by sp00m
It may simplify your code in some use cases:
在某些用例中,它可能会简化您的代码:
List<String> list = // ...;
// with StringBuilder
StringBuilder builder = new StringBuilder();
builder.append("[");
if (!list.isEmpty()) {
builder.append(list.get(0));
for (int i = 1, n = list.size(); i < n; i++) {
builder.append(",").append(list.get(i));
}
}
builder.append("]");
// with StringJoiner
StringJoiner joiner = new StringJoiner(",", "[", "]");
for (String element : list) {
joiner.add(element);
}
回答by Shubham Pandey
StringJoiner is far simpler than using StringBuilder. A very simple code is like
StringJoiner 比使用 StringBuilder 简单得多。一个非常简单的代码就像
StringJoiner sj = new StringJoiner(",");
sj.add("aaa");
sj.add("bbb");
sj.add("ccc");
String result = sj.toString(); //aaa,bbb,ccc