在Java中加入字符串集合的首选惯用语 [英] Preferred Idiom for Joining a Collection of Strings in Java

查看:138
本文介绍了在Java中加入字符串集合的首选惯用语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个字符串集合,你将如何在纯Java中加入它们,而不使用外部库?

Given a Collection of Strings, how would you join them in plain Java, without using an external Library?

给定这些变量:

Collection<String> data = Arrays.asList("Snap", "Crackle", "Pop");
String separator = ", ";
String joined; // let's create this, shall we?

这是我在 Guava

joined = Joiner.on(separator).join(data);

并在 Apache Commons / Lang

joined = StringUtils.join(data, separator);

但是在纯Java中,真的没有比这更好的方法了吗?

But in plain Java, is there really no better way than this?

StringBuilder sb = new StringBuilder();
for(String item : data){
    if(sb.length()>0)sb.append(separator);
    sb.append(item);
}
joined = sb.toString();


推荐答案

em>这样做的方式(如果最好你不意味着最简洁)没有使用Guava是使用Guava内部使用的技术,在你的例子中看起来像这样:

I'd say the best way of doing this (if by best you don't mean "most concise") without using Guava is using the technique Guava uses internally, which for your example would look something like this:

Iterator<String> iter = data.iterator();
StringBuilder sb = new StringBuilder();
if (iter.hasNext()) {
  sb.append(iter.next());
  while (iter.hasNext()) {
    sb.append(separator).append(iter.next());
  }
}
String joined = sb.toString();

这不需要在迭代时进行布尔检查,并且不必进行任何后处理的字符串。

This doesn't have to do a boolean check while iterating and doesn't have to do any postprocessing of the string.

这篇关于在Java中加入字符串集合的首选惯用语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆