1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.collections4.map;
18
19 import java.util.Iterator;
20 import java.util.Map;
21 import java.util.Set;
22
23 import org.apache.commons.collections4.MapIterator;
24 import org.apache.commons.collections4.ResettableIterator;
25
26 /**
27 * Adapts a Map entrySet to the MapIterator interface.
28 *
29 * @param <K> The type of the keys in the map
30 * @param <V> The type of the values in the map
31 * @since 4.0
32 */
33 public class EntrySetToMapIteratorAdapter<K, V> implements MapIterator<K, V>, ResettableIterator<K> {
34
35 /** The adapted Map entry Set. */
36 final Set<Map.Entry<K, V>> entrySet;
37
38 /** The resettable iterator in use. */
39 transient Iterator<Map.Entry<K, V>> iterator;
40
41 /** The currently positioned Map entry. */
42 transient Map.Entry<K, V> entry;
43
44 /**
45 * Create a new EntrySetToMapIteratorAdapter.
46 *
47 * @param entrySet The entrySet to adapt
48 */
49 public EntrySetToMapIteratorAdapter(final Set<Map.Entry<K, V>> entrySet) {
50 this.entrySet = entrySet;
51 reset();
52 }
53
54 /**
55 * Gets the currently active entry.
56 *
57 * @return Map.Entry<K, V>
58 */
59 protected synchronized Map.Entry<K, V> current() {
60 if (entry == null) {
61 throw new IllegalStateException();
62 }
63 return entry;
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 @Override
70 public K getKey() {
71 return current().getKey();
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 @Override
78 public V getValue() {
79 return current().getValue();
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 @Override
86 public boolean hasNext() {
87 return iterator.hasNext();
88 }
89
90 /**
91 * {@inheritDoc}
92 */
93 @Override
94 public K next() {
95 entry = iterator.next();
96 return getKey();
97 }
98
99 /**
100 * {@inheritDoc}
101 */
102 @Override
103 public void remove() {
104 iterator.remove();
105 entry = null;
106 }
107
108 /**
109 * {@inheritDoc}
110 */
111 @Override
112 public synchronized void reset() {
113 iterator = entrySet.iterator();
114 }
115
116 /**
117 * {@inheritDoc}
118 */
119 @Override
120 public V setValue(final V value) {
121 return current().setValue(value);
122 }
123 }