Convert Map to Map

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

How can I convert Map to Map ?

This does not work:

Map map = ne         


        
相关标签:
11条回答
  • 2021-01-31 14:08

    Now that we have Java 8/streams, we can add one more possible answer to the list:

    Assuming that each of the values actually are String objects, the cast to String should be safe. Otherwise some other mechanism for mapping the Objects to Strings may be used.

    Map<String,Object> map = new HashMap<>();
    Map<String,String> newMap = map.entrySet().stream()
         .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
    
    0 讨论(0)
  • 2021-01-31 14:14

    The following will transform your existing entries.

    TransformedMap.decorateTransform(params, keyTransformer, valueTransformer)
    

    Where as

    MapUtils.transformedMap(java.util.Map map, keyTransformer, valueTransformer)
    

    only transforms new entries into your map

    0 讨论(0)
  • 2021-01-31 14:16

    Great solutions here, just one more option that taking into consideration handling of null values:

    Map<String,Object> map = new HashMap<>();
    
    Map<String,String> stringifiedMap = map.entrySet().stream()
                 .filter(m -> m.getKey() != null && m.getValue() !=null)
                 .collect(Collectors.toMap(Map.Entry::getKey, e -> (String)e.getValue()));
    
    0 讨论(0)
  • 2021-01-31 14:19

    There are two ways to do this. One is very simple but unsafe:

    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, String> newMap = new HashMap<String, String>((Map)map);  // unchecked warning
    

    The other way has no compiler warnings and ensures type safety at runtime, which is more robust. (After all, you can't guarantee the original map contains only String values, otherwise why wouldn't it be Map<String, String> in the first place?)

    Map<String, Object> map = new HashMap<String, Object>();
    Map<String, String> newMap = new HashMap<String, String>();
    @SuppressWarnings("unchecked") Map<String, Object> intermediate =
        (Map)Collections.checkedMap(newMap, String.class, String.class);
    intermediate.putAll(map);
    
    0 讨论(0)
  • 2021-01-31 14:19

    Not possible.

    This a little counter-intuitive.

    You're encountering the "Apple is-a fruit" but "Every Fruit is not an Apple"

    Go for creating a new map and checking with instance of with String

    0 讨论(0)
提交回复
热议问题