Java 将 Set<String> 的内容放入单个字符串的最快方法,单词用空格分隔?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3042060/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:55:58  来源:igfitidea点击:

Fastest way to put contents of Set<String> to a single String with words separated by a whitespace?

javastringoptimizationsetwhitespace

提问by Lars Andren

I have a few Set<String>s and want to transform each of these into a single Stringwhere each element of the original Setis separated by a whitespace " ". A naive first approach is doing it like this

我有几个Set<String>s 并且想将它们中的每一个转换为单个String,其中原始的每个元素Set都由空格“”分隔。天真的第一种方法是这样做

Set<String> set_1;
Set<String> set_2;

StringBuilder builder = new StringBuilder();
for (String str : set_1) {
  builder.append(str).append(" ");
}

this.string_1 = builder.toString();

builder = new StringBuilder();
for (String str : set_2) {
  builder.append(str).append(" ");
}

this.string_2 = builder.toString();

Can anyone think of a faster, prettier or more efficient way to do this?

谁能想到更快、更漂亮或更有效的方法来做到这一点?

采纳答案by Sean Patrick Floyd

With commons/lang you can do this using StringUtils.join:

使用 commons/lang 你可以使用StringUtils.join做到这一点:

String str_1 = StringUtils.join(set_1, " ");
String str_1 = StringUtils.join(set_1, " ");

You can't really beat that for brevity.

为简洁起见,您真的无法击败它。

Update:

更新:

Re-reading this answer, I would prefer the other answer regarding Guava's Joinernow. In fact, these days I don't go near apache commons.

重新阅读这个答案,我现在更喜欢关于 Guava's Joiner 的另一个答案。事实上,这些天我不去接近 apache commons。

Another Update:

另一个更新:

Java 8 introduced the method String.join()

Java 8 引入的方法 String.join()

String joined = String.join(",", set);

While this isn't as flexible as the Guava version, it's handy when you don't have the Guava library on your classpath.

虽然这不像 Guava 版本那样灵活,但当你的类路径上没有 Guava 库时它很方便。

回答by Uri

I'm confused about the code replication, why not factor it into a function that takes one set and returns one string?

我对代码复制感到困惑,为什么不将其分解为一个函数,该函数采用一组并返回一个字符串?

Other than that, I'm not sure that there is much that you can do, except maybe giving the stringbuilder a hint about the expected capacity (if you can calculate it based on set size and reasonable expectation of string length).

除此之外,我不确定你能做多少,除了可能给 stringbuilder 一个关于预期容量的提示(如果你可以根据设置的大小和字符串长度的合理预期来计算它)。

There are library functions for this as well, but I doubt they're significantly more efficient.

也有用于此的库函数,但我怀疑它们的效率要高得多。

回答by Cowan

As a counterpoint to Seanizer's commons-lang answer, if you're using Google's Guava Libraries(which I'd consider the 'successor' to commons-lang, in many ways), you'd use Joiner:

作为 Seanizer 的 commons-lang 答案的对立面,如果您使用的是 Google 的Guava 库(我认为它在很多方面都是 commons-lang 的“继承者”),您将使用Joiner

Joiner.on(" ").join(set_1);

with the advantage of a few helper methods to do things like:

借助一些辅助方法来执行以下操作:

Joiner.on(" ").skipNulls().join(set_1);
// If 2nd item was null, would produce "1, 3"

or

或者

Joiner.on(" ").useForNull("<unknown>").join(set_1);
// If 2nd item was null, would produce "1, <unknown>, 3"

It also has support for appending direct to StringBuilders and Writers, and other such niceties.

它还支持直接附加到 StringBuilders 和 Writers,以及其他类似的细节。

回答by tuxdna

I use this method:

我用这个方法:

public static String join(Set<String> set, String sep) {
    String result = null;
    if(set != null) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> it = set.iterator();
        if(it.hasNext()) {
            sb.append(it.next());
        }
        while(it.hasNext()) {
            sb.append(sep).append(it.next());
        }
        result = sb.toString();
    }
    return result;
}

回答by user2808054

I don't have the StringUtil library available (I have no choice over that) so using standard Java I came up with this ..

我没有可用的 StringUtil 库(我别无选择)所以使用标准 Java 我想出了这个 ..

If you're confident that your set data won't include any commas or square brackets, you could use:

如果您确信您的集合数据不包含任何逗号或方括号,则可以使用:

mySet.toString().replaceAll("\[|\]","").replaceAll(","," ");

A set of "a", "b", "c" converts via .toString() to string "[a,b,c]".

一组 "a", "b", "c" 通过 .toString() 转换为字符串 "[a,b,c]"。

Then replace the extra punctuation as necesary.

然后根据需要替换多余的标点符号。

Filth.

污秽。

回答by Jasper de Vries

If you are using Java 8, you can use the native

如果您使用的是 Java 8,则可以使用本

String.join(CharSequence delimiter, Iterable<? extends CharSequence> elements)

method:

方法:

Returns a new Stringcomposed of copies of the CharSequenceelements joined together with a copy of the specified delimiter. For example:

 Set<String> strings = new LinkedHashSet<>();
 strings.add("Java"); strings.add("is");
 strings.add("very"); strings.add("cool");
 String message = String.join("-", strings);
 //message returned is: "Java-is-very-cool"

返回StringCharSequence元素的副本与指定分隔符的副本连接在一起的新组成。例如:

 Set<String> strings = new LinkedHashSet<>();
 strings.add("Java"); strings.add("is");
 strings.add("very"); strings.add("cool");
 String message = String.join("-", strings);
 //message returned is: "Java-is-very-cool"

Setimplements Iterable, so simply use:

Set实现Iterable,所以只需使用:

String.join(" ", set_1);

回答by Ehab Qadah

This can be done by creating a stream out of the set and then combine the elements using a reduce operation as shown below (for more details about Java 8 streams check here):

这可以通过从集合中创建一个流,然后使用 reduce 操作组合元素来完成,如下所示(有关 Java 8 流的更多详细信息,请查看此处):

Optional<String> joinedString = set1.stream().reduce(new 
BinaryOperator<String>() {

     @Override
     public String apply(String t, String u) {

       return t + " " + u;
    }
});
return joinedString.orElse("");

回答by Alexey Rykhalskiy

Maybe a shorter solution:

也许更短的解决方案:

public String test78 (Set<String> set) {
    return set
        .stream()
        .collect(Collectors.joining(" "));
}

or

或者

public String test77 (Set<String> set) {
    return set
        .stream()
        .reduce("", (a,b)->(a + " " + b));
}

but native, definitely faster

但是原生的,绝对更快

public String test76 (Set<String> set) {
    return String.join(" ", set);
}