I found this in redis and was trying to see if there was anything similar in Java. Say I have the following data:
3:1
3:2
3:3
4:1
As you can see non of the data points on their own are unique but the combination is unique. There is a command in redis:
sadd 3 1 2
sadd 3 3
sadd 4 1
That would give me a something like this:
3 -> 1, 2, 3
4 -> 1
By doing something like smembers 3(this would return everything for 3) or smembers 3 2(this would return if the subvalue exists).
I'm wondering what the closest I can get to this functionality within Java?
The Guava MultiMap interface does exactly this. Note that it's up to the particular implementation whether it allows duplicate <K,V> pairs. It sounds like you're after one where the K,V pairs are always unique. If so, have a look at the HashMultimap class.
However, if you want to roll your own, you're probably looking for a combination of Map and Set: Map<Integer,Set<Integer>>
When you add (key, value) elements to the map:
Set<Integer>.map.get(key).put(value);When you want to retrieve all elements with a specific key:
do map.get(key) and iterate over the resultWhen you want to see if a specific key/value pair is in there:
if(map.containsKey(key) && map.get(key).contains(value))For extra credit, you could implement all of this inside a wrapper. The ForwardingMap from guava might be a good place to start.
You can create your own class MultivalueMap like this:
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
public class MultiValueMap<T1, T2> {
public Map<T1, List<T2>> map = null;
public MultiValueMap(){
this.map = new HashMap();
}
public void putList(T1 key, List<T2> list){
map.put(key, list);
}
public void put(T1 key, T2 value){
List<T2> list = null;
if(map.get(key) == null){
list = new ArrayList<T2>();
map.put(key, list);
}
else {
list = map.get(key);
}
list.add(value);
}
public List<T2> get(T1 key){
return map.get(key);
}
public Set<T1> keySet(){
return map.keySet();
}
public Map getMap(){
return this.map;
}
public boolean contains(T1 key, T2 listValue){
List<T2> list = map.get(key);
return list.contains(listValue);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With