Home > Back-end >  Make several "for loops" with different parameters in a single execution
Make several "for loops" with different parameters in a single execution

Time:04-05

In my application I have a for loop that gets data from a map and adds it to a new map that will contain more data from other data sources (several enumClass). I do it this way:

private static Map<String, String> myMapConversion() {

        for (myEnunClassKeyOne key : document.keySet()) {

            String keyObteined = key.toString();
            String value = document.get(key);

            globalConfig.put(convertKey(keyToConversion), value); // Extension function get value of myEnunClassKeyOne key
        }

        return globalConfig;
    }

I have to do the same with other enumClasses and add the data to the same globalConfig map, something like this:

private static Map<String, String> mapConversion() {

        for (myEnunClassKeyONE key : document.keySet()) {

            String keyObteined = key.toString();
            String value = document.get(key);

            globalConfig.put(convertKey(keyToConversion), value); // Extension function get value of myEnunClassKeyOne key
        }

        for (myEnunClassKeyTWO key : document.keySet()) {

            String keyObteined = key.toString();
            String value = document.get(key);

            globalConfig.put(convertKey(keyToConversion), value); // Extension function get value of myEnunClassKeyOne key
        }

        for (myEnunClassKeyTHREE key : document.keySet()) {

            String keyObteined = key.toString();
            String value = document.get(key);

            globalConfig.put(convertKey(keyToConversion), value); // Extension function get value of myEnunClassKeyOne key
        }

        return globalConfig;
    }

Repeating the for loops seems "inelegant" to me. Can you think of a way to do this in a more automated way?

I've tried a few ways, but haven't been able to get it to work. It would have to be java code, although a Kotlin extension function can be accepted

Thanks in advance

CodePudding user response:

In Java, you can create a list of your items and iterate that. I'm assuming these are actually three different documents.

private static Map<String, String> mapConversion() {
    List<Map<?, String>> documents = List.of(document1, document2, document3);
    for (Map<?, String> document : documents) {
        for (Map.Entry<?, String> entry : document.entrySet()) {
            String key = entry.getKey().toString();
            String value = entry.getValue();
            globalConfig.put(convertKey(keyToConversion), value);
        }
    }
    return globalConfig;
}

In Kotlin, you can do this a little more concisely using mapKeysTo:

fun mapConversion(): MutableMap<String, String> {
    listOf(document1, document2, document3).forEach { 
        it.mapKeysTo(globalConifg) { (key, _) -> convertKey(key.toString()) }
    }
    return globalConfig
}
  • Related