Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate strings using Guava?

Tags:

java

guava

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.

like image 780
stacktome Avatar asked Jul 30 '13 14:07

stacktome


People also ask

How do you concatenate strings?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.

How do you concatenate strings in JavaScript?

The + Operator The same + operator you use for adding two numbers can be used to concatenate two strings. You can also use += , where a += b is a shorthand for a = a + b . If the left hand side of the + operator is a string, JavaScript will coerce the right hand side to a string.

Can you use += with strings Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.

What is the best way to concatenate strings in Java?

Using + Operator The + operator is one of the easiest ways to concatenate two strings in Java that is used by the vast majority of Java developers. We can also use it to concatenate the string with other data types such as an integer, long, etc.


3 Answers

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);
like image 51
jlordo Avatar answered Oct 26 '22 18:10

jlordo


"+" 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();
like image 28
Tala Avatar answered Oct 26 '22 17:10

Tala


Try

String inputFile = Joiner.on(",").join(list);
like image 26
Ayub Malik Avatar answered Oct 26 '22 19:10

Ayub Malik