Reputation: 43
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
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();
}
}
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