001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.collections4.map; 018 019import java.util.Iterator; 020import java.util.Map; 021import java.util.Set; 022 023import org.apache.commons.collections4.MapIterator; 024import org.apache.commons.collections4.ResettableIterator; 025 026/** 027 * Adapts a Map entrySet to the MapIterator interface. 028 * 029 * @since 4.0 030 * @version $Id: EntrySetToMapIteratorAdapter.html 972421 2015-11-14 20:00:04Z tn $ 031 */ 032public class EntrySetToMapIteratorAdapter<K, V> implements MapIterator<K, V>, ResettableIterator<K> { 033 034 /** The adapted Map entry Set. */ 035 Set<Map.Entry<K, V>> entrySet; 036 037 /** The resettable iterator in use. */ 038 transient Iterator<Map.Entry<K, V>> iterator; 039 040 /** The currently positioned Map entry. */ 041 transient Map.Entry<K, V> entry; 042 043 /** 044 * Create a new EntrySetToMapIteratorAdapter. 045 * @param entrySet the entrySet to adapt 046 */ 047 public EntrySetToMapIteratorAdapter(final Set<Map.Entry<K, V>> entrySet) { 048 this.entrySet = entrySet; 049 reset(); 050 } 051 052 /** 053 * {@inheritDoc} 054 */ 055 public K getKey() { 056 return current().getKey(); 057 } 058 059 /** 060 * {@inheritDoc} 061 */ 062 public V getValue() { 063 return current().getValue(); 064 } 065 066 /** 067 * {@inheritDoc} 068 */ 069 public V setValue(final V value) { 070 return current().setValue(value); 071 } 072 073 /** 074 * {@inheritDoc} 075 */ 076 public boolean hasNext() { 077 return iterator.hasNext(); 078 } 079 080 /** 081 * {@inheritDoc} 082 */ 083 public K next() { 084 entry = iterator.next(); 085 return getKey(); 086 } 087 088 /** 089 * {@inheritDoc} 090 */ 091 public synchronized void reset() { 092 iterator = entrySet.iterator(); 093 } 094 095 /** 096 * {@inheritDoc} 097 */ 098 public void remove() { 099 iterator.remove(); 100 entry = null; 101 } 102 103 /** 104 * Get the currently active entry. 105 * @return Map.Entry<K, V> 106 */ 107 protected synchronized Map.Entry<K, V> current() { 108 if (entry == null) { 109 throw new IllegalStateException(); 110 } 111 return entry; 112 } 113}