How to concatenate strings using Guava?

本秂侑毒 提交于 2020-01-03 13:55:18

问题


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.

inputFile =joiner.join(inputLine.trim());

But it's giving me an error. I need help to fix this. Many Thanks.


回答1:


You don't need the loop, you can do the following with 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);



回答2:


"+" 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 sb = new StringBuilder("Your string");
 for (String inputLine : list) {
      sb.append(inputLine.trim());
 }
 String inputFile = sb.toString();



回答3:


Try

String inputFile = Joiner.on(",").join(list);



回答4:


If you want to add the trim, go crazy with the lambdas:
Try

String inputFile = Joiner.on(",")
.join(list.stream()
.map(p->p.trim())
.collect(Collectors.toList()));


来源:https://stackoverflow.com/questions/17949435/how-to-concatenate-strings-using-guava

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!