javastringadditionjava-7joiner

Java 7 - String Joiner & add method


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


Solution

  • 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 = ",";
        }
    }