Java Map join to String

Description

Java Map join to String

//package com.demo2s;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Main {
  public static void main(String[] argv) {
     Map<String, Integer> map = new HashMap<>();
     //from   ww w. j a  v a 2  s. c om
     map.put("CSS",1);
     map.put("HTML",1);
     map.put("Java",1);
     map.put("Javascript",1);
     map.put("SQL",1);
     
     String s = map2String(map,":",";");
     System.out.println(s);
  }

  /**
   * This function concatenates the elements of a Map in a string with form
   * "<key1><sepKey><value1><sepEntry>...<keyN><sepKey><valueN>"
   *
   * @param in
   *          - the map to be converted
   * @param sepKey
   *          - the separator to put between key and value
   * @param sepEntry
   *          - the separator to put between map entries
   *
   * @return String
   */
  public static <K, V> String map2String(Map<K, V> in, String sepKey, String sepEntry) {
    if (in == null) {
      return null;
    }

    StringBuilder out = new StringBuilder();
    Iterator<Entry<K, V>> it = in.entrySet().iterator();
    while (it.hasNext()) {
      if (out.length() > 0) {
        out.append(sepEntry);
      }
      Entry<K, V> entry = it.next();
      out.append(entry.getKey() + sepKey + entry.getValue());
    }

    return out.toString();
  }

}



PreviousNext

Related