is it expected that nesting iterators should occur where for loops will break up in real time?

The purpose of this code is still a bit vague even after the latest updates.

If some new data need to be created and appended to the original map numbersAndWords, and they depend somehow on the current state of the original map, then a new temporary map has to be created and populated (using enhanced for loops, Stream API with map/flatMap, whatever). When done, the contents of this new map may be added to the original one, using Map::putAll:

public void exampleOne() {
    Map<String, HashSet<String>> toAppend = new HashMap<>();

    for (Map.Entry<String, HashSet<String>> me : numbersAndWords.entrySet()) {
        for (String str : me.getValue()) {
            System.out.println("Appending for key: " + me.getKey() + "; value=" + str);
            toAppend.computeIfAbsent("three", k -> new HashSet<>())
                    .add("1 2 3"); // or whatever is really needed
        }
    }
    numbersAndWords.putAll(toAppend);

    System.out.println(numbersAndWords);
}

Assuming that the original map is set up like this:

public Example() {
    numbersAndWords = new HashMap<String, HashSet<String>>();
        
    // data
    numbersAndWords.computeIfAbsent("five", k -> new HashSet<>()).add("1 2 3 4 5");
    numbersAndWords.computeIfAbsent("five", k -> new HashSet<>()).add("5 4 3 2 1");
    numbersAndWords.computeIfAbsent("four", k -> new HashSet<>()).add("1 2 3 4");
}

The output is as follows when invoking new Example().exampleOne();:

Appending for key: four; value=1 2 3 4
Appending for key: five; value=1 2 3 4 5
Appending for key: five; value=5 4 3 2 1
{four=[1 2 3 4], five=[1 2 3 4 5, 5 4 3 2 1], three=[1 2 3]}

However, such population of hardcoded values is pretty meaningless because no duplicate entries can be created in the map for a hardcoded key as well as adding the same values to a set is useless.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top