Eshu Manohare
Eshu Manohare

Reputation: 43

how to access 2 keys in a hashmap in same loop?

I am trying to access key1 and key2 in same for loop using Map.Entry. But at a time entry.getKey() returns the current key only. How do I access 2 keys at same time?

for(Map.Entry<Long, NodeDisjoint1> entry : map.entrySet()) {
    long parent1 = findSet(entry.getKey());
    long parent2 = findSet(entry.getKey());
}

Upvotes: 0

Views: 237

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79055

Do it as follows:

Set<Map.Entry<Long, NodeDisjoint1>> entrySet = map.entrySet();
List<Map.Entry<Long, NodeDisjoint1>> entryList = new ArrayList<>(entrySet);
ListIterator<Map.Entry<Long, NodeDisjoint1>> itr = entryList.listIterator();
long parent1, parent2;
while(itr.hasNext()) {
    parent1 = findSet((Entry)itr.next().getKey());
    if(itr.hasNext()) {
        parent2 = findSet((Entry)itr.next().getKey());
        itr.previous();
    }
}

Demo:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(10, 20, 30, 40));
        List<Integer> list = new ArrayList<Integer>(set);
        ListIterator<Integer> itr = list.listIterator();
        while (itr.hasNext()) {
            System.out.println(itr.next());
            if (itr.hasNext()) {
                System.out.println(itr.next());
                itr.previous();
            }
        }
    }
}

Output:

10
20
20
30
30
40
40

Feel free in case of any doubt/issue.

Upvotes: 1

KvaksMan play
KvaksMan play

Reputation: 230

With 1 ENTRYSET you CAN ACCESS ONLY TO 1 KEY AND 1 VALUE

Upvotes: 0

Related Questions