piechuckerr piechuckerr - 3 months ago 18
Java Question

Remove HashMap Key from String

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

country_code
followed by
mobile_number

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("+91","India")
map.put("+94","Sri Lanka")
map.put("+881","Bangladesh")
map.put("+971","UAE")
map.put("+977","Nepal")


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
countryCode
and
mobileNumber
, but country code length(in map's key) varies between 3 and 4. This checking can be done by using
subString()
and
equals()
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

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;
}
Comments