Get an item from a Java Set
Consider using the UnifiedSet
class in Eclipse Collections. It implements the Pool
interface in addition to Set
. Pool
adds Map
-like API for put and get. Pool
is more memory efficient than Map
since it doesn't reserve memory for values, only keys.
UnifiedSet<Integer> pool = UnifiedSet.newSet();
Integer integer = 1;
pool.add(integer);
Assert.assertSame(integer, pool.get(new Integer(integer)));
Note: I am a committer for Eclipse Collections.
If you want to get
from a collection you should use a Map.
(Note most Set implementations are wrappers for a Map)
Map<Key, Value> map = new ....
Value value = map.get(new Key(ID));
In your case, the key and value can be the same type but that is generally a bad idea as keys, like elements of a set, should be immutable.
If HashMap
with id's as keys wouldn't work, then I'd use a HashMap
with your object both as key and value.