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:

我想迭代一個數組,只有在匹配某些條件時才將字符串添加到新字符串中,然后用逗號分隔。如果我可以使用java 8,它將如下所示:

 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.

然而,我被困在7. Guava和其他一些libs似乎都把數組/地圖作為輸入,而不是通過“添加”方法添加。

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

什么是Java 7兼容代碼,可以實現同樣的目標?

Cheers

干杯

AL

AL

2 个解决方案

#1


2  

StringBuilder can do it just fine:

StringBuilder可以做得很好:

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

#2


1  

You can use google guava library's Joiner:

你可以使用谷歌番石榴庫的木匠:

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

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com