Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to iterate and copy the values of HashMap

I want to convert:

Map<String, Map<String, List<Map<String, String>>>> inputMap 

to:

Map<String, Map<String, CustomObject>> customMap

inputMap is provided in the config and is ready but I need to customMap Format. CustomObject will be derived from List<Map<String, String>> using few lines of code in a function.

I have tried a normal way of iterating input map and copying key values in customMap. Is there any efficient way of doing that using Java 8 or some other shortcut?

Map<String, Map<String, List<Map<String, String>>>> configuredMap = new HashMap<>();
Map<String, Map<String, CustomObj>> finalMap = new HashMap<>();


for (Map.Entry<String, Map<String, List<Map<String, String>>>> attributeEntry : configuredMap.entrySet()) {
    Map<String, CustomObj> innerMap = new HashMap<>();
    for (Map.Entry<String, List<Map<String, String>>> valueEntry : attributeEntry.getValue().entrySet()) {
        innerMap.put(valueEntry.getKey(), getCustomeObj(valueEntry.getValue()));
    }
    finalMap.put(attributeEntry.getKey(), innerMap);
}

private CustomObj getCustomeObj(List<Map<String, String>> list) {
    return new CustomObj();
}
like image 686
ghostrider Avatar asked Mar 13 '20 13:03

ghostrider


People also ask

How do I copy values from one HashMap to another?

Given a HashMap, there are three ways one can copy the given HashMap to another: By normally iterating and putting it to another HashMap using put(k, v) method. Using putAll() method. Using copy constructor.

How many ways we can iterate HashMap in Java?

There are generally five ways of iterating over a Map in Java.

Can you iterate through a HashMap?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.


1 Answers

One solution is to stream the entrySet of inputMap, and then use Collectors#toMap twice (once for the outer Map, and once for the inner Map):

Map<String, Map<String, CustomObj>> customMap = inputMap.entrySet()
        .stream()
        .collect(Collectors.toMap(Function.identity(), entry -> {
            return entry.getValue()
                        .entrySet()
                        .stream()
                        .collect(Collectors.toMap(Function.identity(), 
                            entry -> getCustomeObj(entry.getValue())));
        }));
like image 159
Jacob G. Avatar answered Oct 08 '22 23:10

Jacob G.