Though Arvind Kumar Avinash's answer perfectly solves the question, please note that you should reconsider your data structure.
Having a Map
as a key for another Map
is not advisable. You should rather craft another class that serves the purpose of being a key of a Map
. If you are interested in having capitals as keys, consider implementing an immutable class such as this one, in which equals()
and hashcode()
are properly overridden:
public class Capital {
private final String country;
private final String name;
public Capital(String country, String name) {
this.country = country;
this.name = name;
}
public boolean equals(final Object o) {
if (o == this) return true;
if (!(o instanceof Capital)) return false;
final Capital other = (Capital) o;
if (!other.canEqual((Object) this)) return false;
final Object this$country = this.country;
final Object other$country = other.country;
if (this$country == null ? other$country != null : !this$country.equals(other$country)) return false;
final Object this$name = this.name;
final Object other$name = other.name;
if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
return true;
}
protected boolean canEqual(final Object other) {
return other instanceof Capital;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
final Object $country = this.country;
result = result * PRIME + ($country == null ? 43 : $country.hashCode());
final Object $name = this.name;
result = result * PRIME + ($name == null ? 43 : $name.hashCode());
return result;
}
public String toString() {
return "Capital(country=" + this.country + ", name=" + this.name + ")";
}
}
If you want to get rid of the boilerplate code, consider using the Lombok Project. The above-listed class is the delomboked version of the following code:
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor
public class Capital {
private final String country;
private final String name;
}
Update after Holger's comment:
Other implementations for equals()
and hashCode()
than the above-mentioned, delomboked version are possible, differing in some criterias such as code style and performance. Same as Holger, I think the delomboked implementation should not be hand-crafted. It is simply the implementation that results through the usage of the Lombok @EqualsAndHashCode
annotation.
There are requirements to be fulfilled in order to properly override hashCode()
and equals()
:
Though performance and good code-sytle are important, they are not amongst these requirements. With the usage of Lombok, in my opinion, code-style is less important, since the code is generated. One usually does not see it during development.
The canEqual()
method is present since Lombok also generates it.