Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java Map Enum keys to Map String keys

I have the following map:

Map<DataFields, String> myMap;

But I need to convert it to the following:

Map<String, String> myMap;

My best feeble attempt which doesn't even compile is:

myMap.keySet().stream().map(k -> k.name()).collect(Collectors.toMap(k, v)
like image 432
jiveturkey Avatar asked Feb 27 '18 18:02

jiveturkey


4 Answers

You need to stream the entrySet() (so you have both the keys and the values), and collect them to a map:

Map<String, String> result =
    myMap.entrySet()
         .stream()
         .collect(Collectors.toMap(e -> e.getKey().name(), e -> e.getValue()));
like image 195
Mureinik Avatar answered Nov 11 '22 05:11

Mureinik


Map<String, String> result = myMap
    .entrySet() // iterate over all entries (object with tow fields: key and value)
    .stream() // create a stream
    .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue()));
        // collect to map: convert enum Key value toString() and copy entry value
like image 38
kasopey Avatar answered Nov 11 '22 05:11

kasopey


Another way of doing same without Collectors helper. Using entryset will make it very easy to map.

  map.entrySet()
                .stream()
                .collect(
                        () -> new HashMap<String, String>(),
                        (Map newMap, Map.Entry<DataFields, String> entry) -> {
                            newMap.put(entry.getKey().name(), entry.getValue());
                        }
                        ,
                        (Map map1, Map map2) -> {
                            map.putAll(map2);
                        }
                );
like image 2
Vinay Prajapati Avatar answered Nov 11 '22 04:11

Vinay Prajapati


A Java 8, succint way to do it (without streams):

Map<String, String> result = new HashMap<>();
myMap.forEach((k, v) -> result.put(k.name(), v));
like image 2
fps Avatar answered Nov 11 '22 04:11

fps