简体   繁体   中英

save null values as multiple keys where null has a single meaning

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 (eg "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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM