piechuckerr piechuckerr - 1 year ago 83
Java Question

Remove HashMap Key from String

I have mobile numbers in database table column, in a format of

followed by

So Mobile Number format is like this,

+91123456789 // country code of India is +91 followed by mobile number
+97188888888 // Country code of UAE +971

I have one HashMap containing CountryCodes of 5 countries like this,

map.put("+94","Sri Lanka")

My Bean Structure is something like this

class UserDetails {

// other fields
String countryCode;
String mobileNumber;

Now my task is to take the mobile number from Database table column and split it in two parts and set
, but country code length(in map's key) varies between 3 and 4. This checking can be done by using
but I don't think it's correct way, So what would be the elegant(may be checking in
map key
) way to solve this issue?

Answer Source

IMHO a single map is better. An example;

public static void main(String args[]) throws Exception {
    Map<String, String> map = new HashMap<>();
    put(map, "+91", "India");
    put(map, "+94", "Sri Lanka");
    put(map, "+881", "Bangladesh");
    put(map, "+971", "UAE");
    put(map, "+977", "Nepal");
    map = Collections.unmodifiableMap(map);

    String mobileNumber = "+91123456789";
    System.out.println(countryCode(map.keySet(), mobileNumber));

private static void put(Map<String, String> map, String key, String value) {
    if (countryCode(map.keySet(), key) != null) {
        throw new IllegalArgumentException("...");
    map.put(key, value);

public static String countryCode(Set<String> countryCodes, String number) {
    if (number == null || number.length() < 3) {
        throw new IllegalArgumentException("...");
    String code = number.substring(0, 3);
    if (!countryCodes.contains(code)) {
        if (number.length() > 3) {
            code = number.substring(0, 4);
            if (!countryCodes.contains(code)) {
                code = null;
        } else {
            code = null;
    return code;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download