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.io.IOException;
020import java.io.ObjectInputStream;
021import java.io.ObjectOutputStream;
022import java.io.Serializable;
023import java.util.AbstractList;
024import java.util.AbstractSet;
025import java.util.ArrayList;
026import java.util.Collection;
027import java.util.HashMap;
028import java.util.Iterator;
029import java.util.List;
030import java.util.ListIterator;
031import java.util.Map;
032import java.util.NoSuchElementException;
033import java.util.Set;
034
035import org.apache.commons.collections4.OrderedMap;
036import org.apache.commons.collections4.OrderedMapIterator;
037import org.apache.commons.collections4.ResettableIterator;
038import org.apache.commons.collections4.iterators.AbstractUntypedIteratorDecorator;
039import org.apache.commons.collections4.keyvalue.AbstractMapEntry;
040import org.apache.commons.collections4.list.UnmodifiableList;
041
042/**
043 * Decorates a <code>Map</code> to ensure that the order of addition is retained
044 * using a <code>List</code> to maintain order.
045 * <p>
046 * The order will be used via the iterators and toArray methods on the views.
047 * The order is also returned by the <code>MapIterator</code>.
048 * The <code>orderedMapIterator()</code> method accesses an iterator that can
049 * iterate both forwards and backwards through the map.
050 * In addition, non-interface methods are provided to access the map by index.
051 * <p>
052 * If an object is added to the Map for a second time, it will remain in the
053 * original position in the iteration.
054 * <p>
055 * <strong>Note that ListOrderedMap is not synchronized and is not thread-safe.</strong>
056 * If you wish to use this map from multiple threads concurrently, you must use
057 * appropriate synchronization. The simplest approach is to wrap this map
058 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
059 * exceptions when accessed by concurrent threads without synchronization.
060 * <p>
061 * <strong>Note that ListOrderedMap doesn't work with
062 * {@link java.util.IdentityHashMap IdentityHashMap}, {@link CaseInsensitiveMap},
063 * or similar maps that violate the general contract of {@link java.util.Map}.</strong>
064 * The <code>ListOrderedMap</code> (or, more precisely, the underlying <code>List</code>)
065 * is relying on {@link Object#equals(Object) equals()}. This is fine, as long as the
066 * decorated <code>Map</code> is also based on {@link Object#equals(Object) equals()},
067 * and {@link Object#hashCode() hashCode()}, which
068 * {@link java.util.IdentityHashMap IdentityHashMap}, and
069 * {@link CaseInsensitiveMap} don't: The former uses <code>==</code>, and
070 * the latter uses {@link Object#equals(Object) equals()} on a lower-cased
071 * key.
072 * <p>
073 * This class is {@link Serializable} starting with Commons Collections 3.1.
074 *
075 * @since 3.0
076 * @version $Id: ListOrderedMap.html 972397 2015-11-14 15:01:49Z tn $
077 */
078public class ListOrderedMap<K, V>
079        extends AbstractMapDecorator<K, V>
080        implements OrderedMap<K, V>, Serializable {
081
082    /** Serialization version */
083    private static final long serialVersionUID = 2728177751851003750L;
084
085    /** Internal list to hold the sequence of objects */
086    private final List<K> insertOrder = new ArrayList<K>();
087
088    /**
089     * Factory method to create an ordered map.
090     * <p>
091     * An <code>ArrayList</code> is used to retain order.
092     *
093     * @param <K>  the key type
094     * @param <V>  the value type
095     * @param map  the map to decorate, must not be null
096     * @return a new list ordered map
097     * @throws NullPointerException if map is null
098     * @since 4.0
099     */
100    public static <K, V> ListOrderedMap<K, V> listOrderedMap(final Map<K, V> map) {
101        return new ListOrderedMap<K, V>(map);
102    }
103
104    //-----------------------------------------------------------------------
105    /**
106     * Constructs a new empty <code>ListOrderedMap</code> that decorates
107     * a <code>HashMap</code>.
108     *
109     * @since 3.1
110     */
111    public ListOrderedMap() {
112        this(new HashMap<K, V>());
113    }
114
115    /**
116     * Constructor that wraps (not copies).
117     *
118     * @param map  the map to decorate, must not be null
119     * @throws NullPointerException if map is null
120     */
121    protected ListOrderedMap(final Map<K, V> map) {
122        super(map);
123        insertOrder.addAll(decorated().keySet());
124    }
125
126    //-----------------------------------------------------------------------
127    /**
128     * Write the map out using a custom routine.
129     *
130     * @param out  the output stream
131     * @throws IOException
132     * @since 3.1
133     */
134    private void writeObject(final ObjectOutputStream out) throws IOException {
135        out.defaultWriteObject();
136        out.writeObject(map);
137    }
138
139    /**
140     * Read the map in using a custom routine.
141     *
142     * @param in  the input stream
143     * @throws IOException
144     * @throws ClassNotFoundException
145     * @since 3.1
146     */
147    @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
148    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
149        in.defaultReadObject();
150        map = (Map<K, V>) in.readObject(); // (1)
151    }
152
153    // Implement OrderedMap
154    //-----------------------------------------------------------------------
155    @Override
156    public OrderedMapIterator<K, V> mapIterator() {
157        return new ListOrderedMapIterator<K, V>(this);
158    }
159
160    /**
161     * Gets the first key in this map by insert order.
162     *
163     * @return the first key currently in this map
164     * @throws NoSuchElementException if this map is empty
165     */
166    public K firstKey() {
167        if (size() == 0) {
168            throw new NoSuchElementException("Map is empty");
169        }
170        return insertOrder.get(0);
171    }
172
173    /**
174     * Gets the last key in this map by insert order.
175     *
176     * @return the last key currently in this map
177     * @throws NoSuchElementException if this map is empty
178     */
179    public K lastKey() {
180        if (size() == 0) {
181            throw new NoSuchElementException("Map is empty");
182        }
183        return insertOrder.get(size() - 1);
184    }
185
186    /**
187     * Gets the next key to the one specified using insert order.
188     * This method performs a list search to find the key and is O(n).
189     *
190     * @param key  the key to find previous for
191     * @return the next key, null if no match or at start
192     */
193    public K nextKey(final Object key) {
194        final int index = insertOrder.indexOf(key);
195        if (index >= 0 && index < size() - 1) {
196            return insertOrder.get(index + 1);
197        }
198        return null;
199    }
200
201    /**
202     * Gets the previous key to the one specified using insert order.
203     * This method performs a list search to find the key and is O(n).
204     *
205     * @param key  the key to find previous for
206     * @return the previous key, null if no match or at start
207     */
208    public K previousKey(final Object key) {
209        final int index = insertOrder.indexOf(key);
210        if (index > 0) {
211            return insertOrder.get(index - 1);
212        }
213        return null;
214    }
215
216    //-----------------------------------------------------------------------
217    @Override
218    public V put(final K key, final V value) {
219        if (decorated().containsKey(key)) {
220            // re-adding doesn't change order
221            return decorated().put(key, value);
222        }
223        // first add, so add to both map and list
224        final V result = decorated().put(key, value);
225        insertOrder.add(key);
226        return result;
227    }
228
229    @Override
230    public void putAll(final Map<? extends K, ? extends V> map) {
231        for (final Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
232            put(entry.getKey(), entry.getValue());
233        }
234    }
235
236    /**
237     * Puts the values contained in a supplied Map into the Map starting at
238     * the specified index.
239     *
240     * @param index the index in the Map to start at.
241     * @param map the Map containing the entries to be added.
242     * @throws IndexOutOfBoundsException if the index is out of range [0, size]
243     */
244    public void putAll(int index, final Map<? extends K, ? extends V> map) {
245        if (index < 0 || index > insertOrder.size()) {
246            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + insertOrder.size());
247        }
248        for (final Map.Entry<? extends K, ? extends V> entry : map.entrySet()) {
249            final K key = entry.getKey();
250            final boolean contains = containsKey(key);
251            // The return value of put is null if the key did not exist OR the value was null
252            // so it cannot be used to determine whether the key was added
253            put(index, entry.getKey(), entry.getValue());
254            if (!contains) {
255                // if no key was replaced, increment the index
256                index++;
257            } else {
258                // otherwise put the next item after the currently inserted key
259                index = indexOf(entry.getKey()) + 1;
260            }
261        }
262    }
263
264    @Override
265    public V remove(final Object key) {
266        V result = null;
267        if (decorated().containsKey(key)) {
268            result = decorated().remove(key);
269            insertOrder.remove(key);
270        }
271        return result;
272    }
273
274    @Override
275    public void clear() {
276        decorated().clear();
277        insertOrder.clear();
278    }
279
280    //-----------------------------------------------------------------------
281    /**
282     * Gets a view over the keys in the map.
283     * <p>
284     * The Collection will be ordered by object insertion into the map.
285     *
286     * @see #keyList()
287     * @return the fully modifiable collection view over the keys
288     */
289    @Override
290    public Set<K> keySet() {
291        return new KeySetView<K>(this);
292    }
293
294    /**
295     * Gets a view over the keys in the map as a List.
296     * <p>
297     * The List will be ordered by object insertion into the map.
298     * The List is unmodifiable.
299     *
300     * @see #keySet()
301     * @return the unmodifiable list view over the keys
302     * @since 3.2
303     */
304    public List<K> keyList() {
305        return UnmodifiableList.unmodifiableList(insertOrder);
306    }
307
308    /**
309     * Gets a view over the values in the map.
310     * <p>
311     * The Collection will be ordered by object insertion into the map.
312     * <p>
313     * From Commons Collections 3.2, this Collection can be cast
314     * to a list, see {@link #valueList()}
315     *
316     * @see #valueList()
317     * @return the fully modifiable collection view over the values
318     */
319    @Override
320    public Collection<V> values() {
321        return new ValuesView<V>(this);
322    }
323
324    /**
325     * Gets a view over the values in the map as a List.
326     * <p>
327     * The List will be ordered by object insertion into the map.
328     * The List supports remove and set, but does not support add.
329     *
330     * @see #values()
331     * @return the partially modifiable list view over the values
332     * @since 3.2
333     */
334    public List<V> valueList() {
335        return new ValuesView<V>(this);
336    }
337
338    /**
339     * Gets a view over the entries in the map.
340     * <p>
341     * The Set will be ordered by object insertion into the map.
342     *
343     * @return the fully modifiable set view over the entries
344     */
345    @Override
346    public Set<Map.Entry<K, V>> entrySet() {
347        return new EntrySetView<K, V>(this, this.insertOrder);
348    }
349
350    //-----------------------------------------------------------------------
351    /**
352     * Returns the Map as a string.
353     *
354     * @return the Map as a String
355     */
356    @Override
357    public String toString() {
358        if (isEmpty()) {
359            return "{}";
360        }
361        final StringBuilder buf = new StringBuilder();
362        buf.append('{');
363        boolean first = true;
364        for (final Map.Entry<K, V> entry : entrySet()) {
365            final K key = entry.getKey();
366            final V value = entry.getValue();
367            if (first) {
368                first = false;
369            } else {
370                buf.append(", ");
371            }
372            buf.append(key == this ? "(this Map)" : key);
373            buf.append('=');
374            buf.append(value == this ? "(this Map)" : value);
375        }
376        buf.append('}');
377        return buf.toString();
378    }
379
380    //-----------------------------------------------------------------------
381    /**
382     * Gets the key at the specified index.
383     *
384     * @param index  the index to retrieve
385     * @return the key at the specified index
386     * @throws IndexOutOfBoundsException if the index is invalid
387     */
388    public K get(final int index) {
389        return insertOrder.get(index);
390    }
391
392    /**
393     * Gets the value at the specified index.
394     *
395     * @param index  the index to retrieve
396     * @return the key at the specified index
397     * @throws IndexOutOfBoundsException if the index is invalid
398     */
399    public V getValue(final int index) {
400        return get(insertOrder.get(index));
401    }
402
403    /**
404     * Gets the index of the specified key.
405     *
406     * @param key  the key to find the index of
407     * @return the index, or -1 if not found
408     */
409    public int indexOf(final Object key) {
410        return insertOrder.indexOf(key);
411    }
412
413    /**
414     * Sets the value at the specified index.
415     *
416     * @param index  the index of the value to set
417     * @param value  the new value to set
418     * @return the previous value at that index
419     * @throws IndexOutOfBoundsException if the index is invalid
420     * @since 3.2
421     */
422    public V setValue(final int index, final V value) {
423        final K key = insertOrder.get(index);
424        return put(key, value);
425    }
426
427    /**
428     * Puts a key-value mapping into the map at the specified index.
429     * <p>
430     * If the map already contains the key, then the original mapping
431     * is removed and the new mapping added at the specified index.
432     * The remove may change the effect of the index. The index is
433     * always calculated relative to the original state of the map.
434     * <p>
435     * Thus the steps are: (1) remove the existing key-value mapping,
436     * then (2) insert the new key-value mapping at the position it
437     * would have been inserted had the remove not occurred.
438     *
439     * @param index  the index at which the mapping should be inserted
440     * @param key  the key
441     * @param value  the value
442     * @return the value previously mapped to the key
443     * @throws IndexOutOfBoundsException if the index is out of range [0, size]
444     * @since 3.2
445     */
446    public V put(int index, final K key, final V value) {
447        if (index < 0 || index > insertOrder.size()) {
448            throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + insertOrder.size());
449        }
450
451        final Map<K, V> m = decorated();
452        if (m.containsKey(key)) {
453            final V result = m.remove(key);
454            final int pos = insertOrder.indexOf(key);
455            insertOrder.remove(pos);
456            if (pos < index) {
457                index--;
458            }
459            insertOrder.add(index, key);
460            m.put(key, value);
461            return result;
462        }
463        insertOrder.add(index, key);
464        m.put(key, value);
465        return null;
466    }
467
468    /**
469     * Removes the element at the specified index.
470     *
471     * @param index  the index of the object to remove
472     * @return the removed value, or <code>null</code> if none existed
473     * @throws IndexOutOfBoundsException if the index is invalid
474     */
475    public V remove(final int index) {
476        return remove(get(index));
477    }
478
479    /**
480     * Gets an unmodifiable List view of the keys which changes as the map changes.
481     * <p>
482     * The returned list is unmodifiable because changes to the values of
483     * the list (using {@link java.util.ListIterator#set(Object)}) will
484     * effectively remove the value from the list and reinsert that value at
485     * the end of the list, which is an unexpected side effect of changing the
486     * value of a list.  This occurs because changing the key, changes when the
487     * mapping is added to the map and thus where it appears in the list.
488     * <p>
489     * An alternative to this method is to use the better named
490     * {@link #keyList()} or {@link #keySet()}.
491     *
492     * @see #keyList()
493     * @see #keySet()
494     * @return The ordered list of keys.
495     */
496    public List<K> asList() {
497        return keyList();
498    }
499
500    //-----------------------------------------------------------------------
501    static class ValuesView<V> extends AbstractList<V> {
502        private final ListOrderedMap<Object, V> parent;
503
504        @SuppressWarnings("unchecked")
505        ValuesView(final ListOrderedMap<?, V> parent) {
506            super();
507            this.parent = (ListOrderedMap<Object, V>) parent;
508        }
509
510        @Override
511        public int size() {
512            return this.parent.size();
513        }
514
515        @Override
516        public boolean contains(final Object value) {
517            return this.parent.containsValue(value);
518        }
519
520        @Override
521        public void clear() {
522            this.parent.clear();
523        }
524
525        @Override
526        public Iterator<V> iterator() {
527            return new AbstractUntypedIteratorDecorator<Map.Entry<Object, V>, V>(parent.entrySet().iterator()) {
528                public V next() {
529                    return getIterator().next().getValue();
530                }
531            };
532        }
533
534        @Override
535        public V get(final int index) {
536            return this.parent.getValue(index);
537        }
538
539        @Override
540        public V set(final int index, final V value) {
541            return this.parent.setValue(index, value);
542        }
543
544        @Override
545        public V remove(final int index) {
546            return this.parent.remove(index);
547        }
548    }
549
550    //-----------------------------------------------------------------------
551    static class KeySetView<K> extends AbstractSet<K> {
552        private final ListOrderedMap<K, Object> parent;
553
554        @SuppressWarnings("unchecked")
555        KeySetView(final ListOrderedMap<K, ?> parent) {
556            super();
557            this.parent = (ListOrderedMap<K, Object>) parent;
558        }
559
560        @Override
561        public int size() {
562            return this.parent.size();
563        }
564
565        @Override
566        public boolean contains(final Object value) {
567            return this.parent.containsKey(value);
568        }
569
570        @Override
571        public void clear() {
572            this.parent.clear();
573        }
574
575        @Override
576        public Iterator<K> iterator() {
577            return new AbstractUntypedIteratorDecorator<Map.Entry<K, Object>, K>(parent.entrySet().iterator()) {
578                public K next() {
579                    return getIterator().next().getKey();
580                }
581            };
582        }
583    }
584
585    //-----------------------------------------------------------------------
586    static class EntrySetView<K, V> extends AbstractSet<Map.Entry<K, V>> {
587        private final ListOrderedMap<K, V> parent;
588        private final List<K> insertOrder;
589        private Set<Map.Entry<K, V>> entrySet;
590
591        public EntrySetView(final ListOrderedMap<K, V> parent, final List<K> insertOrder) {
592            super();
593            this.parent = parent;
594            this.insertOrder = insertOrder;
595        }
596
597        private Set<Map.Entry<K, V>> getEntrySet() {
598            if (entrySet == null) {
599                entrySet = parent.decorated().entrySet();
600            }
601            return entrySet;
602        }
603
604        @Override
605        public int size() {
606            return this.parent.size();
607        }
608        @Override
609        public boolean isEmpty() {
610            return this.parent.isEmpty();
611        }
612
613        @Override
614        public boolean contains(final Object obj) {
615            return getEntrySet().contains(obj);
616        }
617
618        @Override
619        public boolean containsAll(final Collection<?> coll) {
620            return getEntrySet().containsAll(coll);
621        }
622
623        @Override
624        @SuppressWarnings("unchecked")
625        public boolean remove(final Object obj) {
626            if (obj instanceof Map.Entry == false) {
627                return false;
628            }
629            if (getEntrySet().contains(obj)) {
630                final Object key = ((Map.Entry<K, V>) obj).getKey();
631                parent.remove(key);
632                return true;
633            }
634            return false;
635        }
636
637        @Override
638        public void clear() {
639            this.parent.clear();
640        }
641
642        @Override
643        public boolean equals(final Object obj) {
644            if (obj == this) {
645                return true;
646            }
647            return getEntrySet().equals(obj);
648        }
649
650        @Override
651        public int hashCode() {
652            return getEntrySet().hashCode();
653        }
654
655        @Override
656        public String toString() {
657            return getEntrySet().toString();
658        }
659
660        @Override
661        public Iterator<Map.Entry<K, V>> iterator() {
662            return new ListOrderedIterator<K, V>(parent, insertOrder);
663        }
664    }
665
666    //-----------------------------------------------------------------------
667    static class ListOrderedIterator<K, V> extends AbstractUntypedIteratorDecorator<K, Map.Entry<K, V>> {
668        private final ListOrderedMap<K, V> parent;
669        private K last = null;
670
671        ListOrderedIterator(final ListOrderedMap<K, V> parent, final List<K> insertOrder) {
672            super(insertOrder.iterator());
673            this.parent = parent;
674        }
675
676        public Map.Entry<K, V> next() {
677            last = getIterator().next();
678            return new ListOrderedMapEntry<K, V>(parent, last);
679        }
680
681        @Override
682        public void remove() {
683            super.remove();
684            parent.decorated().remove(last);
685        }
686    }
687
688    //-----------------------------------------------------------------------
689    static class ListOrderedMapEntry<K, V> extends AbstractMapEntry<K, V> {
690        private final ListOrderedMap<K, V> parent;
691
692        ListOrderedMapEntry(final ListOrderedMap<K, V> parent, final K key) {
693            super(key, null);
694            this.parent = parent;
695        }
696
697        @Override
698        public V getValue() {
699            return parent.get(getKey());
700        }
701
702        @Override
703        public V setValue(final V value) {
704            return parent.decorated().put(getKey(), value);
705        }
706    }
707
708    //-----------------------------------------------------------------------
709    static class ListOrderedMapIterator<K, V> implements OrderedMapIterator<K, V>, ResettableIterator<K> {
710        private final ListOrderedMap<K, V> parent;
711        private ListIterator<K> iterator;
712        private K last = null;
713        private boolean readable = false;
714
715        ListOrderedMapIterator(final ListOrderedMap<K, V> parent) {
716            super();
717            this.parent = parent;
718            this.iterator = parent.insertOrder.listIterator();
719        }
720
721        public boolean hasNext() {
722            return iterator.hasNext();
723        }
724
725        public K next() {
726            last = iterator.next();
727            readable = true;
728            return last;
729        }
730
731        public boolean hasPrevious() {
732            return iterator.hasPrevious();
733        }
734
735        public K previous() {
736            last = iterator.previous();
737            readable = true;
738            return last;
739        }
740
741        public void remove() {
742            if (readable == false) {
743                throw new IllegalStateException(AbstractHashedMap.REMOVE_INVALID);
744            }
745            iterator.remove();
746            parent.map.remove(last);
747            readable = false;
748        }
749
750        public K getKey() {
751            if (readable == false) {
752                throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID);
753            }
754            return last;
755        }
756
757        public V getValue() {
758            if (readable == false) {
759                throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID);
760            }
761            return parent.get(last);
762        }
763
764        public V setValue(final V value) {
765            if (readable == false) {
766                throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID);
767            }
768            return parent.map.put(last, value);
769        }
770
771        public void reset() {
772            iterator = parent.insertOrder.listIterator();
773            last = null;
774            readable = false;
775        }
776
777        @Override
778        public String toString() {
779            if (readable == true) {
780                return "Iterator[" + getKey() + "=" + getValue() + "]";
781            }
782            return "Iterator[]";
783        }
784    }
785
786}