日期:2014-05-20  浏览次数:20642 次

java hashMap获取键值对
hashMap里有键值对 Draft_dwg=abc、 Draft_pdf=cdf、Draft_wmf=gph
我现在如何把hashmap中的key得到,并且拼接成字符串的形式,比如字符串1得到 “Draft_dwg, Draft_pdf, Draft_wmf”
字符串2得到"abc,cdf,gph" 因为这两个字符串要插入到sql语句,insert into flat (字符串1) values (字符串2)

------解决方案--------------------
Map map = new HashMap(); 
Iterator iter = map.entrySet().iterator(); 
while (iter.hasNext()) { 
Map.Entry entry = (Map.Entry) iter.next(); 
Object key = entry.getKey(); 
Object val = entry.getValue(); 


------解决方案--------------------
Java code

public static void main(String[] args) {
    LinkedHashMap<String, String> map = new LinkedHashMap<>();
    map.put("Draft_dwg", "abc");
    map.put("Draft_pdf", "cdf");
    map.put("Draft_wmf", "gph");
    System.out.println(createInsertSQL(map, "flat"));
}

public static String createInsertSQL(Map<String, String> map, String table) {
    StringBuilder keys = new StringBuilder();
    StringBuilder values = new StringBuilder();
    boolean first = true;
    for (Entry<String, String> entry : map.entrySet()) {
        if (!first) {
            keys.append(", ");
            values.append(", ");
        }
        first = false;
        keys.append(entry.getKey());
        values.append("\"" + entry.getValue() + "\"");
    }
    return "insert into " + table + " (" + keys + ") values (" + values + ")";
}

------解决方案--------------------
补充一下,map有个keySet方法可以得到所有的key,另sql语句的value是用单引号扩起来的
Java code

Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("Draft_dwg", "abc");
        map.put("Draft_pdf", "cdf");
        map.put("Draft_wmf", "gph");
        StringBuffer cols = new StringBuffer();
        StringBuffer vals = new StringBuffer();
        boolean first = true;

        for (String key : map.keySet())
        {
            if (!first)
            {
                cols.append(", ");
                vals.append(", ");
            }
            first = false;
            cols.append(key);
            vals.append("'" + map.get(key) + "'");
        }
        System.out.println("insert into   flat  (" + cols + ") values (" + vals+ ")");

------解决方案--------------------
Java code

  Map<String, String> map = new HashMap<String, String>(); 
        
         map.put("Draft_dwg", "abc");
        map.put("Draft_pdf", "cdf");
        map.put("Draft_wmf", "gph");
        
        Set<String> keys = map.keySet() ; 
        Collection<String> values = map.values() ;
        
        System.out.println( keys ); 
        System.out.println( values );