Reputation: 1302
In my current project, I need following type of data structure
Map<String, Map<String,Set<String>>, Set<subscriber>>
As per my knowledge, Java does not support this kind of data structure (Kindly correct me if I am wrong). Or (you can suggest me “how can I achieve this data type of data structure in Java).
Is there any third party library, which supports above mentioned data structure and operations on it?
Upvotes: 0
Views: 390
Reputation: 5565
why not:
Map<String, Object[]>
and then create a 2 length object array to hold your Map<String,Set<String>>
and Set<subscriber>
It's a bit of a hack, but it's a solution
EDIT: I like the custom object idea, way better and more type safe!
Upvotes: 1
Reputation: 76908
Java doesn't supply a simple "Pair" class so you'd need to write a wrapper class and use it in your Map:
class Wrapper {
public Map<String,Set<String>> myMap = new HashMap<String,Set<String>>();
public Set<Subscriber> mySet = new TreeSet<Subscriber>();
}
Map <String, Wrapper> myMapOfWrappers = new HashMap<String, Wrapper>();
(The Wrapper
class here is a simple example, you could provide getters/setters, etc as appropriate for your use case)
Edit to add: You added a comment under your question at the same time I posted this. Even though you accepted it as the answer, your comment says you are looking for two keys. You may want to rethink how you're approaching the problem. Alex shows in his example how you'd have to do this. Using mutable data as a key in a Map
can cause a lot of problems should the contents change, which is what all his code is preventing. Implementing a equals()
and hashCode()
to prevent that is often not trivial.
Upvotes: 3
Reputation: 13951
If you really want maps to act as keys in your data structure, then I think this is what you want:
static Map<String,Set<String>> makeUnmodifiable(Map<String,Set<String>> m) {
Map<String,Set<String>> map = new HashMap<String,Set<String>>();
for (Map.Entry<String,Set<String>> entry : m.entrySet()) {
map.add(entry.getKey(), Collections.unmodifiableSet(entry.getValue()));
}
return Collections.unmodifiableMap(map);
}
static class Pair {
final String first;
final Map<String,Set<String>> second;
Pair(String first, Map<String,Set<String>> second) {
this.first = first;
this.second = second != null ? makeUnmodifiable(second) : null;
}
public void equals(Object o) {
...
}
public int hashCode() {
...
}
}
Map<Pair,Set<Subscriber>> myMap;
Note that you MUST override equals and hashCode in the custom Pair class in order for this to work properly.
Upvotes: 2
Reputation: 7011
A possible solution would be to create an object to house all of your information and then make a Map with key String
and value CustomObject
Upvotes: 4
Reputation: 14053
A map is a key/value
object, so you can't have a Map<String, Map, Set>
to start.
Upvotes: 4