Key Existence Check in Hashmap

Key existence check in HashMap

Do you ever store a null value? If not, you can just do:

Foo value = map.get(key);
if (value != null) {
...
} else {
// No such key
}

Otherwise, you could just check for existence if you get a null value returned:

Foo value = map.get(key);
if (value != null) {
...
} else {
// Key might be present...
if (map.containsKey(key)) {
// Okay, there's a key but the value is null
} else {
// Definitely no such key
}
}

Checking the existence of the key before adding a newhashmap

Assumption:

Keys in Maps are unique, so if you try to insert a new record with a key already present, there will be a "collision" and the value corresponding to that key in the map will be overwritten.

Answering your question:
containsKey() is the correct way, especially in your case where you do a check at runtime, you have the possibility to check at each iteration if the current value you want to insert is already present in the whole map, because containsKey() goes to probe all the keys in the map.

Map MAP_SA = new HashMap()

while(iterator.hasNext()){
org = iterator.next();

if(!MAP_SA.containsKey(org.getExtended8())){ // check all over the map
MAP_SA.put(org.getExtended8(),org.getName());
}else
System.out.println("Error: the key already exists");

}

Java : How to check if a key is exists in a Hashmap

You should override the equals and hashCode methods of your Position object so that two elements with the same value for x and y are equals.

@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}

Position otherPos = (Position) obj;
return x == otherPos.x
&& y == otherPos.y;
}

@Override
public int hashCode() {
return Objects.hash(x, y);
}

How can I check if a hashmap contains a key of a custom class type?

You are checking if the Map contains a key of a specific instance of class B (not the class itself).

If you need to check if the Map contains a key of class B you can do:

boolean hasClass = map.keySet().stream().anyMatch(B.class::isInstance);

Check if hash map key is present before retrieving value

Before Java 8, you have to explicitly do the check :

String firstName = map.get(UserDetail.FIRST_NAME);

// null guard
if (firstName != null){
// invoke a method on firstName
}

After Java 8, you could use the Map.getOrDefault() method.

For example :

String firstName = map.getOrDefault(UserDetail.FIRST_NAME, "");

Now, in some cases, having a default value is not suitable as you want to do the processing only if the value is contained in the map and that is also not null.

In this configuration, a better way to address it is using Optional combined with ifPresent() :

Optional<String> optional = Optional.of(map.get(UserDetail.FIRST_NAME));
optional.ifPresent((s)->myProcessing());

You could also inline Optional if it used once :

Optional.of(map.get(UserDetail.FIRST_NAME))
.ifPresent((s)->myProcessing());

Check the existence of a HashMap key

The containsKey should be very slightly slower because it results in an extra function call (it just calls getEntry) (it could get optimised away, I'm not sure whether Java will do so). containsKey looks like:

public boolean containsKey(Object key) {
return getEntry(key) != null;
}

But note that containsKey could on the other hand be very slightly faster on other Map implementations (but probably not those in the standard Java API).

Generally my implementations look like: (avoiding the need for containsKey)

int[] arr = map.get(100);
if (arr == null) // doesn't exist
// do stuff
else // exists
// do stuff with arr

The below would definitely be slower than the above: (if the items you look for exist a reasonable amount of the time)

if (!map.containsKey(100)) // doesn't exist
// do stuff
else // exists
{
int[] arr = map.get(100);
// do stuff with arr
}

Edit: Thanks to zvzdhk for providing the source of containsKey. I should actually have checked.

Creating a method to check if a value exists in a generic HashMap in Java?

Why are you re-inventing the wheel? Map has containsKey() which does exactly as you want.

Check in Map of list if exists value for specific key Java 8

You can simply use m.get("Name2"), place the (nullable) result into an Optional and then use a mapping:

boolean result = Optional.ofNullable(m.get("Name2"))
.map(l -> l.stream().anyMatch(s -> s.contains("@")))
.orElse(false);

This is preferable to looping over the entry set, as HashMap.get is O(1) and iterating over the entry set is O(n).



Related Topics



Leave a reply



Submit