3

I've tried to iterate over the items in a HashMap MyMap in order to get all the 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 executes first "while loop" successfully, it restarts over again with the first key of the hashmap. During the second "while loop" I want to start NodeY from the following element of currently-chosen NodeX.

Here is my desired output:

  • loop 1: (a,b),(a,c),(a,d),(a,e),....
  • loop 2: (b,c),(b,d),(b,e),....
  • loop3: (c,d),(c,e),.....
    ...
4
  • entry1.next(); where does entry1 come from? Commented Apr 4, 2018 at 6:48
  • 2
    First of all, use generics so you don't need to keep casting to String and Map.Entry everywhere. Secondly, you seem to be interested in only the keys, so use keySet(), not entrySet(). Lastly, your code doesn't make much sense. Of course the whole map will be iterated in the second while. Are you really sure you want to use a map? Commented Apr 4, 2018 at 6:50
  • Please watch out for edits made by other user and learn out of it, do not copy and paste your old question. Like the regards should not be there. Commented Apr 4, 2018 at 7:01
  • Do you need the value in that Map, seems it would be simpler with a List here. And the iteration on index would give you a simple solution too. Commented Apr 4, 2018 at 7:04

2 Answers 2

2

In term of clean logic, I prefer to not use two iterator but simply use an index based solution. You can simply convert the Set into an list to be able to get each item based on the index. (can be easier solution but I do

    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 iterate every item (but the last) and the inner loop will iterate from directly 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 is not really more efficient since you still need to create an array to be able to do that, but if you don't need the map but can directly use a List, you will be able to do the same logic quite easily.

Sign up to request clarification or add additional context in comments.

Comments

1

What you are looking to do is to double iterate the keyset of a hashmap in Java. Here is a sample script showing how this can be done. The secret sauce is to only print key pairs such that the first key is strictly less than the second key. This prevents the chance of printing duplicates, though the algorithm is a brute force O(n^2) double iteration over the entire keyset.

Map<Character, Integer> map = new HashMap<>();
map.put('a', 1);
map.put('b', 2);
map.put('c', 3);
map.put('d', 4);

Iterator<Character> i1 = map.keySet().iterator();

while (i1.hasNext()) {
    char k1 = i1.next();
    Iterator<Character> i2 = map.keySet().iterator();

    while (i2.hasNext()) {
        char k2 = i2.next();
        if (k1 < k2) {
            System.out.println("(" + k1 + ", " + k2 + ")");
        }
    }
}

(a, b)
(a, c)
(a, d)
(b, c)
(b, d)
(c, d)

Demo

6 Comments

Can I use for loop for hash map starting from specific key to the end in the inner loop?
@user1690298 Unfortunately the keyset for a hashmap is not ordered as far as I know, so there is no "middle" in the sense which you mention. But why do you need to do this? Are you very concerned about performance? You might have to pull the keys into a different data structure.
Yes I concern about performance since I use hashmap to build a trust network for recommender system
Even if we do as you say, it won't change the complexity much. I think it would still be roughly O(n^2).
Thanks for your response Tim. The keys (user IDs) are unique numbers. an I order the map to get the list behavior?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.