Reputation:
I am trying to choose a Java data structure with the following properties
Key: Long
Value: Set
Is there a structure that I can index into and add values to the Set?
For example say I have the object <1, [a,b,c]> and I want to add d this so that the output is <1, [a,b,c,d]>?
Can this be easily done in java?
Upvotes: 2
Views: 989
Reputation: 8376
As others have stated, you will be best served by a Map<Long, Set<String>>
. In your example:
Map<Long, Set<String>> myMap = new HashMap<Long, Set<String>>();
Set<String> initialSet = new HashSet<String>();
initialSet.add("a");
initialSet.add("b");
initialSet.add("c");
myMap.put(1, initialSet);
myMap.get(1).add("d"); // to add the "d"
Upvotes: 1
Reputation: 6473
If you are able to use a third party library, Guava has Multimaps, which make it easy to store multiple values for a single key.
For example:
import com.google.common.collect.HashMultimap;
HashMultimap<Long, String> multimap = HashMultimap.create();
multimap.put(1L, "a");
multimap.put(1L, "b");
multimap.put(1L, "c");
multimap.put(1L, "d");
See the docs.
Upvotes: 2
Reputation: 18068
Just use:
HashMap<Long, String> map = new HashMap<Long, ArrayList<String>>();
If you want to add something to it just
ArrayList<String> list = map.get(KEY_YOU_WANT_TO_CHECK);
if(list == null){
list = new ArrayList<String>();
list.add(STRING_YOU_WANT_TO_ADD);
map.put(KEY_YOU_WANT_TO_CHECK,list);
}else{
list.add(STRING_YOU_WANT_TO_ADD);
}
Of course you can replace ArrayList
with HashSet
also with Vector
and TreeSet
Upvotes: 0
Reputation: 1820
Yes a Map would work.
Map yourmap = new HashMap<Long, List<String>>();
Upvotes: 0
Reputation: 240928
I have the object
<1, [a,b,c]>
and I want to add d this so that the output is<1, [a,b,c,d]>
?
Map<Long, Set<Character>
would work good
Upvotes: 0