Java – while for iterator hashmap

while for iterator hashmap… here is a solution to the problem.

while for iterator hashmap

I tried iterating through the items in HashMap MyMap to get all possible combination pairs of 2 keys (nodes:

).

I used this code:

Iterator Iterator1= MyMap.entrySet().iterator();

while (Iterator1.hasNext() ) {
    Map.Entry X = (Map.Entry) Iterator1.next();
    NodeX=(String) X.getKey();                       
    Iterator Iterator2= MyMap.entrySet().iterator();

while (Iterator2.hasNext() ) {
        Map.Entry Y = (Map.Entry) Iterator2.next();
        NodeY= (String) Y.getKey();                                        
        System.out.println("{ "+NodeX+" , "+NodeY+" }");
    }

}

Each time, the compiler successfully executes the first “while loop” and then starts over with the first key of the hashmap. During the second “while loop”, I want to launch NodeY from the following elements of the currently selected NodeX.

This is the output I want :

  • Cycle 1: (a,b),(a,c),(a,d),(a,e),….
  • Loop 2: (b,c),(b,d),(b,e),….
  • loop3: (c,d),(c,e),…..

Solution

In terms of concise logic, I prefer not to use two iterators and just use an index-based solution. You can simply convert a Set to a list to be able to get each item based on the index. (Probably a simpler solution, but I did

.)

    Map<String, String> map = new HashMap<>();
    map.put("a", "");
    map.put("b", "");
    map.put("c", "");
    map.put("d", "");
    map.put("e", "");
    map.put("f", "");

List<String> list = new ArrayList<String>(map.keySet());

for (int i = 0; i < list.size() - 1; ++i) {
        String s = list.get(i);
        for (int j = i + 1; j < list.size(); ++j) {
            System.out.format("(%s, %s)%n", s, list.get(j));
        }
    }

The outer loop iterates

over every item (except the last item), and the inner loop iterates directly from the next item until the end.

a b
a c
a d
a e
a f
b c
b d
b e
b f
c d
c e
c f
d e
d f
e f

This doesn’t really improve efficiency because you still need to create an array to do that, but if you don’t need map but can use List directly, you’ll be able to easily execute the same logic.

Related Problems and Solutions