将 Set内容放入其中的最快方法到单个字符串,单词之间用空格分隔?

发布于 2024-09-05 20:23:27 字数 531 浏览 3 评论 0原文

我有一些 Set,并且希望将其中的每一个转换为单个 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();

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

甜柠檬 2024-09-12 20:23:27

使用commons/lang,您可以使用StringUtils.join

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

为了简洁起见,你无法真正击败它。

更新:

重新阅读这个答案,我现在更喜欢有关 Guava 的 Joiner 的其他答案。事实上,这些天我不再接近 apache commons。

另一个更新:

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

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

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

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

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 Joiner now. In fact, these days I don't go near apache commons.

Another Update:

Java 8 introduced the method 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.

笙痞 2024-09-12 20:23:27

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

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

方法:

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

 设置 strings = new LinkedHashSet<>();
 字符串.add(“Java”);字符串.add(“是”);
 strings.add("非常");字符串.add(“酷”);
 字符串消息 = String.join("-", strings);
 //返回的消息是:“Java-is-very-cool”

设置 实现了 Iterable,所以只需使用:

String.join(" ", set_1);

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

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

method:

Returns a new String composed of copies of the CharSequence elements 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"

Set implements Iterable, so simply use:

String.join(" ", set_1);
栖迟 2024-09-12 20:23:27

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

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

具有一些辅助方法的优点,可以执行以下操作:

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

或者

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

它还支持直接附加到 StringBuilders 和 Writers 等礼貌。

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:

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.

假面具 2024-09-12 20:23:27

也许是一个更短的解决方案:

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

或者

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

但是原生的,肯定更快

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

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);
}
萌︼了一个春 2024-09-12 20:23:27

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

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

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

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

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

污秽。

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

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]".

Then replace the extra punctuation as necesary.

Filth.

假情假意假温柔 2024-09-12 20:23:27

我用这个方法:

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;
}

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;
}
萝莉病 2024-09-12 20:23:27

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

除此之外,我不确定您可以做很多事情,除了向字符串生成器提供有关预期容量的提示(如果您可以根据设置大小和字符串长度的合理预期来计算它)。

也有用于此目的的库函数,但我怀疑它们的效率是否明显更高。

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).

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

零崎曲识 2024-09-12 20:23:27

这可以通过从集合中创建一个流,然后使用归约操作组合元素来完成,如下所示(有关 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("");

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):

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

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

       return t + " " + u;
    }
});
return joinedString.orElse("");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文