Java 7 - String Joiner & add method

6.1k views Asked by At

I want to iterate through an array and only add the string to the new string if certain conditions are matched, and then seperate with a comma. IF I could use java 8 it would look like this:

 StringJoiner col = new StringJoiner(",");
 StringJoiner val = new StringJoiner(",");
 //First Iteration: Create the Statement
 for(String c : columns) {
     //Your PDF has a matching formfield 
     if(pdf.hasKey(c)) {
         col.add(c);
         val.add("?");
      }
  }

However I am stuck on 7. Guava and some of the other libs all seem to take an array/map as input, as opposed to adding via a "add" method.

Whats some Java 7 compatiable code that would acheive the same thing?

Cheers

AL

2

There are 2 answers

0
VGR On BEST ANSWER

StringBuilder can do it just fine:

StringBuilder col = new StringBuilder();
StringBuilder val = new StringBuilder();
String separator = "";
for (String c : columns) {
    if (pdf.hasKey(c)) {
        col.append(separator).append(c);
        val.append(separator).append("?");
        separator = ",";
    }
}
0
The Java Guy On

You can use google guava library's Joiner:

private static String reduce(List<String> values) {
    return Joiner.on(",").skipNulls().join(values);
}