问题
I would like to know how can I iterate in a 2Dimensional HashMap? I am creating an Object TrueStringMap2D that does the following: It will be a map 2D, i mean 2 keys and one value.
But the iterator implemented here is not functional.. i didnt know how to redefine the Iterator method in TrueStringMap2D :S (if possible should be remove in the iterator() functional) Anyone can help? Thankyou very much!!
回答1:
I'll reinterpret the question into something similar that I enjoy answering, and then hopefully the answer to that question is useful to you.
Here's the question I'll answer:
How do I write an iterator that iterates over all values in a
Map<String, Map<String, String>>
?
This is how I would solve it:
class TwoDimIterator implements Iterator<String> {
Iterator<Map<String, String>> outerIter;
Iterator<String> innerIter = Collections.<String>emptyList().iterator();
public TwoDimIterator(Map<String, Map<String, String>> twoDimMap) {
outerIter = twoDimMap.values().iterator();
advanceInner();
}
@Override
public boolean hasNext() {
return innerIter.hasNext();
}
@Override
public String next() {
String toReturn = innerIter.next();
advanceInner();
return toReturn;
}
private void advanceInner() {
while (!innerIter.hasNext()) {
if (!outerIter.hasNext()) {
innerIter = Collections.<String>emptyList().iterator();
return;
}
innerIter = outerIter.next().values().iterator();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
Test code:
class Test {
public static void main(String[] args) {
// Create a map
Map<String, Map<String, String>> twoDimMap =
new HashMap<String, Map<String, String>>();
// Fill it
Map<String, String> innerA = new HashMap<String, String>();
innerA.put("1", "A1");
innerA.put("2", "A2");
Map<String, String> innerB = new HashMap<String, String>();
innerB.put("1", "B1");
innerB.put("2", "B2");
twoDimMap.put("A", innerA);
twoDimMap.put("B", innerB);
// Create an iterator for the values:
Iterator<String> twoDimIter = new TwoDimIterator(twoDimMap);
while (twoDimIter.hasNext())
System.out.println(twoDimIter.next());
}
}
Output:
A2
A1
B2
B1
来源:https://stackoverflow.com/questions/10484575/iterator-in-a-2dimensional-map