java 如何使用番石榴连接字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17949435/
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
How to concatenate strings using Guava?
提问by stacktome
I wrote some code to concatenate Strings:
我写了一些代码来连接字符串:
String inputFile = "";
for (String inputLine : list) {
inputFile +=inputLine.trim());
}
But I can't use +
to concatenate, so I decide to go with Guava. So I need to use Joiner.
但是我不能+
用来连接,所以我决定用番石榴。所以我需要使用Joiner。
inputFile =joiner.join(inputLine.trim());
But it's giving me an error. I need help to fix this. Many Thanks.
但它给了我一个错误。我需要帮助来解决这个问题。非常感谢。
回答by jlordo
You don't need the loop, you can do the following with Guava:
您不需要循环,您可以使用 Guava 执行以下操作:
// trim the elements:
List<String> trimmed = Lists.transform(list, new Function<String, String>() {
@Override
public String apply(String in) {
return in.trim();
}
});
// join them:
String joined = Joiner.on("").join(trimmed);
回答by Tala
"+" should work. Don't use libraries when you're having problems. Try to understand the nature. Otherrwise you'll have a very complicated code with hundreds of libraries :))
“+”应该可以工作。遇到问题时不要使用库。尝试了解自然。否则,您将拥有包含数百个库的非常复杂的代码:))
This should work instead.
这应该起作用。
for (String inputLine : list) {
inputFile += inputLine.trim();
}
And you might also want to use Stringbuilder
你可能还想使用Stringbuilder
StringBuilder sb = new StringBuilder("Your string");
for (String inputLine : list) {
sb.append(inputLine.trim());
}
String inputFile = sb.toString();
回答by Ayub Malik
Try
尝试
String inputFile = Joiner.on(",").join(list);
回答by Daniel Schmidt
If you want to add the trim, go crazy with the lambdas:
Try
如果您想添加修剪,请为 lambda 疯狂:
尝试
String inputFile = Joiner.on(",")
.join(list.stream()
.map(p->p.trim())
.collect(Collectors.toList()));