How to concatenate strings using Guava?

I wrote code to concatenate strings:

String inputFile = ""; for (String inputLine : list) { inputFile +=inputLine.trim()); } 

But I can't use + to concatenate, so I decided to go with Guava. Therefore, I need to use Joiner.

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

But that gives me an error. I need help to fix this. Many thanks.

+4
source share
4 answers

You do not need a 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); 
+19
source

"+" should work. Do not use libraries in case of problems. Try to understand nature. Another thing, you will have very complex code with hundreds of libraries :))

That should work.

 for (String inputLine : list) { inputFile += inputLine.trim(); } 

And you can also use Stringbuilder

  StringBuilder sb = new StringBuilder("Your string"); for (String inputLine : list) { sb.append(inputLine.trim()); } String inputFile = sb.toString(); 
+5
source

Try

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

If you want to add a finish, go crazy with lambda:
Try

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

Source: https://habr.com/ru/post/1494308/


All Articles