I need a multiple key map and I want to use null values as keys. I am using HashBasedTable which does not allow null keys.
Table<String, String, JsonObject> table = HashBasedTable.create();
String key1= null, key2= null;
table.put(key1, key2, value);
How can I achieve the same. Please help. Thanks
You can use a null object, in that case a string which you know is not part of the possible set of strings (e.g. "Unknown"
):
Table<String, String, JsonObject> table = HashBasedTable.create();
String key1 = MoreObjects.firstNonNull(realKey1, "Unknown"),
key2 = MoreObjects.firstNonNull(realKey2, "Unknown");
table.put(key1, key2, value);
You can also use Optional<String>
to wrap your keys instead, and then your null object becomes Optional.empty()
(or Optional.absent()
if you use Guava's Optional
):
Table<Optional<String>, Optional<String>, JsonObject> table = HashBasedTable.create();
Optional<String> key1 = Optional.ofNullable(realKey1),
key2 = Optional.ofNullable(realKey2);
table.put(key1, key2, value);