HashMap to return default value for non-found keys?

后端 未结 14 2208
别跟我提以往
别跟我提以往 2020-11-27 14:05

Is it possible to have a HashMap return a default value for all keys that are not found in the set?

14条回答
  •  死守一世寂寞
    2020-11-27 14:24

    I needed to read the results returned from a server in JSON where I couldn't guarantee the fields would be present. I'm using class org.json.simple.JSONObject which is derived from HashMap. Here are some helper functions I employed:

    public static String getString( final JSONObject response, 
                                    final String key ) 
    { return getString( response, key, "" ); }  
    public static String getString( final JSONObject response, 
                                    final String key, final String defVal ) 
    { return response.containsKey( key ) ? (String)response.get( key ) : defVal; }
    
    public static long getLong( final JSONObject response, 
                                final String key ) 
    { return getLong( response, key, 0 ); } 
    public static long getLong( final JSONObject response, 
                                final String key, final long defVal ) 
    { return response.containsKey( key ) ? (long)response.get( key ) : defVal; }
    
    public static float getFloat( final JSONObject response, 
                                  final String key ) 
    { return getFloat( response, key, 0.0f ); } 
    public static float getFloat( final JSONObject response, 
                                  final String key, final float defVal ) 
    { return response.containsKey( key ) ? (float)response.get( key ) : defVal; }
    
    public static List getList( final JSONObject response, 
                                            final String key ) 
    { return getList( response, key, new ArrayList() ); }   
    public static List getList( final JSONObject response, 
                                            final String key, final List defVal ) { 
        try { return response.containsKey( key ) ? (List) response.get( key ) : defVal; }
        catch( ClassCastException e ) { return defVal; }
    }   
    

提交回复
热议问题