If a perl-hash is declared like so:
use warnings;
use strict;
my %h;
I can then check for the existence of keys within this hash with exists:
if (exists $h{k3}) {
print "k3 exists\n";
}
else {
print "k3 doesn't exist\n";
}
Since k3 does not exist, the script prints k3 doesn't exist.
I can also check for the existence ka in k3:
if (exists $h{k3}{ka}) {
print "k3 ka exists\n";
}
else {
print "k3 ka doesn't exist\n";
}
Unfortunately, this creates the key k3, so that another
if (exists $h{k3}) {
print "k3 exists\n";
}
else {
print "k3 doesn't exist\n";
}
now prints k3 exists.
This is a bit unfortunate for my purposes. I'd rather not want perl to create the k3 key.
I can, of course, check for ka within k3 with something like
if (exists $h{k3} and exists $h{k3}{ka})
which doesn't create the key k3. But I wonder if there is a shorter (and imho cleaner) way to check for ka within k3.
Edit The question was marked as duplicate. Unfortunately, the only answer in the referred question that mentions no autovivification has only one upvote there, and is not marked as accepted answer. For my purposes, the no autovification is the feature I needed to know (and that I was unknowingly after). So, I leave my question here as I think the accepted answer in the other question is not the optimal one.
Unfortunatly, nobody so far answered with no autovification which I would like to accept. I might therefore answer my own question.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
You cannot do it by Java collection. You can use Multimap it supports duplicate keys but it also support duplicate keys and value pairs. Best solution for you is use Multimap and check if value already exist then dont add it.
Overview. The map implementations provided by the Java JDK don't allow duplicate keys. If we try to insert an entry with a key that exists, the map will simply overwrite the previous entry.
Keys are unique once added to the HashMap , but you can know if the next one you are going to add is already present by querying the hash map with containsKey(..) or get(..) method.
The simplest thing is to nest your ifs:
if (exists $h{k3}) {
print "k3 exists\n";
if (exists $h{k3}{ka}) {
print "k3 ka exists\n";
}
else {
print "k3 ka doesn't exist\n";
}
}
else {
print "k3 doesn't exist\n";
}
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