Reputation: 41
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:
Upvotes: 3
Views: 178
Reputation: 14572
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.
Upvotes: 2
Reputation: 522406
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)
Upvotes: 1