Reputation: 51
When writing a Java program, I face a problem as follows:
Map<Object, Map<Object, Map<Object, Object>>> map = new HashMap<>();
/**
* put operations
**/
Map<Object, Map<Object, Object>> a = null;
Map<Object, Object> b = null;
Object c = null;
a = map.get(/*some object*/);
if(a != null) {
b = a.get(/*some object*/);
}
if(b != null) {
c = b.get(/*some object*/);
}
if(c != null) {
/*do what I want to do*/
}
If I want to be sure c
is not null
, I need to add an "if" three times to ensure that the code can run without exception. Is there a better way to do it?
Upvotes: 0
Views: 114
Reputation: 19201
I think that the getOrDefault-method of the Map
interface could work here. Especially if you combine it with the Optional class as follows:
Map<Object, Map<Object, Map<Object, Object>>> map = new HashMap<>();
Map<Object, Map<Object, Object>> a = map.getOrDefault("", Collections.emptyMap());
Map<Object, Object> b = a.getOrDefault("", Collections.emptyMap());
Optional.ofNullable(b.get("")).ifPresent(c -> {/* Do what I want to do */});
This way you simply use getOrDefault
to retrieve empty maps (which I personally like better than null
values. The Optional.ofNullable
is a null
-safe way of creating an Optional
object and you can do what you want to do in the lambda expression.
Both Optional
and Map.getOrDefault
are part of Java 8.
Upvotes: 0
Reputation: 906
Encapsulate required functionality in a class implementing something like this:
interface ThreeKeysMap {
void put(Object keyA, Object keyB, Object keyC, Object value);
Object get(Object keyA, Object keyB, Object keyC);
}
Alternatively, you could create a class for your composite key:
public class ThreeKey {
public Object keyA;
public Object keyB;
public Object keyC;
// TODO: MUST override equals and hashCode methods or map won't work!!!!
}
and use it as a key for your map: Map<ThreeKey, Object> map = new HashMap<>();
Upvotes: 2
Reputation: 178411
You can create a class Key<T,E>
that will hold your first pairs of objects, and than create a map
Map<Key<T,E>, Object>
This seems much more neat to me, because it seems you use the first two objects as a key, and the nested dictionary approach is less elegant for such a task.
Remember that if you follow this approach - you have to override equals()
and hashCode()
, and depending on usages - sometimes also compareTo()
Upvotes: 0