string - Java custom implode methode like in PHP -


i trying replicate php function implode() in java.

this made:

private string implode(string delimiter, map<string, string> map){     stringbuilder sb = new stringbuilder();     for(entry<string, string> e : map.entryset()){       sb.append(" "+delimiter+" ");       sb.append(" " + e.getkey() + " = '" + e.getvalue() + "' ");    }     return sb.tostring(); } 

testing:

map<string, string> mylist = new hashmap<string, string>(); mylist.put("address", "something1"); mylist.put("last_name", "something2"); mylist.put("first_name", "something3");  update_database("dummy", mylist, "");  public void update_database(string table, map<string, string> update_list, string condition){    string query = "update " + table + " set ";     query += implode(",", update_list) + " " + condition;      system.out.println(query); } 

output:

update dummy set , address = 'something' , last_name = 'something2', first_name = 'something3'

if worked mysql before, know it's not valid query because string query start ",".

how can format string correct query?

you try this:

own implementation

private string implode(string delimiter, map<string, string> map){     boolean first = true;    stringbuilder sb = new stringbuilder();     for(entry<string, string> e : map.entryset()){       if (!first) sb.append(" "+delimiter+" ");       sb.append(" " + e.getkey() + " = '" + e.getvalue() + "' ");       first = false;    }     return sb.tostring(); } 

stringutils

another solution use public static string join(collection collection, char separator)


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -