Convert Map to Map

后端 未结 11 1829
暗喜
暗喜 2021-01-31 13:27

How can I convert Map to Map ?

This does not work:

Map map = ne         


        
11条回答
  •  鱼传尺愫
    2021-01-31 14:00

    As you are casting from Object to String I recommend you catch and report (in some way, here I just print a message, which is generally bad) the exception.

        Map map = new HashMap(); //Object is containing String
        Map newMap =new HashMap();
    
        for (Map.Entry entry : map.entrySet()) {
            try{
                newMap.put(entry.getKey(), (String) entry.getValue());
            }
            catch(ClassCastException e){
                System.out.println("ERROR: "+entry.getKey()+" -> "+entry.getValue()+
                                   " not added, as "+entry.getValue()+" is not a String");
            }
        }
    

提交回复
热议问题