Zbarcea Christian
Zbarcea Christian

Reputation: 9548

Java custom implode methode like in PHP

I am trying to replicate the php function implode() in Java.

This is what I 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 you worked with mysql before, you know that it's not a valid query because the string query start with ",".

How can I format my string to get a correct query?

Upvotes: 2

Views: 2272

Answers (2)

Francisco Spaeth
Francisco Spaeth

Reputation: 23903

You could try something like 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 would be to use public static String join(Collection collection, char separator)

Upvotes: 6

Daniel Kaplan
Daniel Kaplan

Reputation: 67440

You don't need to write this yourself. There's already a library with this functionality named guava made by google. It has a class called a Joiner. Here's an example:

Joiner joiner = Joiner.on("; ").skipNulls();
return joiner.join("Harry", null, "Ron", "Hermione");

This returns the string "Harry; Ron; Hermione". Note that all input elements are converted to strings using Object.toString() before being appended.

Upvotes: 3

Related Questions