A very sleazy way to use a HashSet as a Map
/*
* Copyright 2016 Payball Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.payball.db.core.collection;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Stream;
/**
* <p>
* This class is a clone of the {@link HashSet} collection exposing
* the internal HashMap and providing convenience methods
* for accessing and storing key/value pairs.
* </p>
* <p>
* Analogously to the HackSet, when adding entries using
* the Set interface, the key entry must be modified to discard
* any associated value. This will prevent taking into account
* the hash code of the value for the global hash code of the key.
* </p>
* This way, the set will contain key/value pairs with the proper key
* and null value e.g. :
* <pre>[ key = extraProp, value = null ] , [ key = extraProp2, value = null ]</pre>
* <p>
* Key/Value pairs can be stored using the method :
* </p>
* <pre>map.put(K key, V value)</pre>
* <p>
* In order to retrieve values from the <i>MapHackSet</i> the user can use the convenience
* method :
* </p>
* </p>
* <pre>map.get(E key)</pre>
* </p>
*/
public class MapHackSet<K,V> extends AbstractSet<Map.Entry<K,V>> implements Set<Map.Entry<K,V>>, Cloneable
{
/**
* The internal hash map
*/
protected transient HashMap<Map.Entry<K,V>,V> map;
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
public MapHackSet() {
map = new HashMap<>();
}
/**
* Constructs a new set containing the elements in the specified
* collection. The <tt>HashMap</tt> is created with default load factor
* (0.75) and an initial capacity sufficient to contain the elements in
* the specified collection.
*
* @param c the collection whose elements are to be placed into this set
* @throws NullPointerException if the specified collection is null
*/
public MapHackSet(Collection<? extends Map.Entry<K,V>> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public MapHackSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
/**
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* the specified initial capacity and default load factor (0.75).
*
* @param initialCapacity the initial capacity of the hash table
* @throws IllegalArgumentException if the initial capacity is less
* than zero
*/
public MapHackSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the hash map
* @param loadFactor the load factor of the hash map
* @param dummy ignored (distinguishes this
* constructor from other int, float constructor.)
* @throws IllegalArgumentException if the initial capacity is less
* than zero, or if the load factor is nonpositive
*/
public MapHackSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
*
* @return an Iterator over the elements in this set
* @see ConcurrentModificationException
*/
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return map.keySet().iterator();
}
/**
* Returns the number of elements in this set (its cardinality).
*
* @return the number of elements in this set (its cardinality)
*/
public int size() {
return map.size();
}
/**
* Returns <tt>true</tt> if this set contains no elements.
*
* @return <tt>true</tt> if this set contains no elements
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* Returns <tt>true</tt> if this set contains the specified element.
* More formally, returns <tt>true</tt> if and only if this set
* contains an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* @param o element whose presence in this set is to be tested
* @return <tt>true</tt> if this set contains the specified element
*/
public boolean contains(Object o) {
return map.containsKey(o);
}
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(Map.Entry<K,V> e) {
return map.put(new Entry<>(e.getKey(), null), e.getValue())==null;
}
/**
* Removes the specified element from this set if it is present.
* More formally, removes an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>,
* if this set contains such an element. Returns <tt>true</tt> if
* this set contained the element (or equivalently, if this set
* changed as a result of the call). (This set will not contain the
* element once the call returns.)
*
* @param o object to be removed from this set, if present
* @return <tt>true</tt> if the set contained the specified element
*/
public boolean remove(Object o) {
return map.remove(o)!=null;
}
/**
* Removes all of the elements from this set.
* The set will be empty after this call returns.
*/
public void clear() {
map.clear();
}
/**
* Returns a shallow copy of this <tt>MapHackSet</tt> instance: the elements
* themselves are not cloned.
*
* @return a shallow copy of this set
*/
@SuppressWarnings("unchecked")
public Object clone() {
try {
MapHackSet<K,V> newSet = (MapHackSet<K,V>) super.clone();
newSet.map = (HashMap<Map.Entry<K,V>, V>) map.clone();
return newSet;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
* and <em>fail-fast</em> {@link Spliterator} over the elements in this
* set.
*
* <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
* {@link Spliterator#DISTINCT}. Overriding implementations should document
* the reporting of additional characteristic values.
*
* @return a {@code Spliterator} over the elements in this set
* @since 1.8
*/
@Override
public Spliterator<Map.Entry<K,V>> spliterator() {
return map.keySet().spliterator();
}
@Override
public Stream<Map.Entry<K, V>> stream() {
return map.keySet().stream();
}
/**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
*
* @param action The action to be performed for each element
* @throws NullPointerException if the specified action is null
* @implSpec <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
* @since 1.8
*/
@Override
public void forEach(Consumer<? super Map.Entry<K, V>> action) {
map.keySet().forEach(action);
}
/**
* Returns a possibly parallel {@code Stream} with this collection as its
* source. It is allowable for this method to return a sequential stream.
* <p>
* <p>This method should be overridden when the {@link #spliterator()}
* method cannot return a spliterator that is {@code IMMUTABLE},
* {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
* for details.)
*
* @return a possibly parallel {@code Stream} over the elements in this
* collection
* @implSpec The default implementation creates a parallel {@code Stream} from the
* collection's {@code Spliterator}.
* @since 1.8
*/
@Override
public Stream<Map.Entry<K, V>> parallelStream() {
return map.keySet().parallelStream();
}
/**
* Retrieves the object for the given key
*
* @param key the key
* @return the object
*/
public V get(K key) {
return map.get(new Entry<K,V>(key, null));
}
/**
* Sets the value for the given key
*
* @param key the key
* @param value the value
*/
public void put(K key, V value) {
map.put(new Entry<>(key, null), value);
}
/**
* Sets the value for the given key
*
* @param key the key
*/
public void put(Map.Entry<K,V> key, V value) {
map.put(new Entry<>(key.getKey(), null), value);
}
/**
* Retrieves the map.
*
* @return the map
*/
public HashMap<Map.Entry<K,V>,V> getMap() {
return map;
}
}