Efficient way to delete values from hashmap object

13,766

Solution 1

List remList = Arrays.asList(rem);
for (Iterator it = map.keySet().iterator(); it.hasNext();) {
    String key = (String) it.next();
    String[] tokens = key.split("-");
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i];
        if (remList.contains(token)) {
            it.remove();
            break;
        }
     }
}

And an updated version with adding functionality based on your latest comment on this answer:

private static Map getMapWithDeletions(Map map, String[] rem) {
    Map pairs = new HashMap();
    for (int i = 0; i < rem.length; i++) {
        String keyValue = rem[i];
        String[] pair = keyValue.split("@", 2);
        if (pair.length == 2) {
            pairs.put(pair[0], pair[1]);
        }
    }
    Set remList = pairs.keySet();
    for (Iterator it = map.keySet().iterator(); it.hasNext();) {
        String key = (String) it.next();
        String[] tokens = key.split("-");
        for (int i = 0; i < tokens.length; i++) {
            String token = tokens[i];
            if (remList.contains(token)) {
                it.remove();
                pairs.remove(token);
                break;
            }
        }
    }
    map.putAll(pairs);
    return map;
}

Solution 2

Edited based on edited question.

Loop through the keySet of the hashmap. When you find a key that starts with x you are looking for remove it from the map.

Something like:

for(String[] key: map.keySet()){
   if(key.length>0 && x.equals(key[0])){
      map.remove(key);
    }
}
Share:
13,766
user569125
Author by

user569125

Updated on August 02, 2022

Comments

  • user569125
    user569125 almost 2 years

    I have HashMap object contains a key x-y-z with corresponding value test-test1-test2.

    Map<String,String> map = new HashMap<String,String>(); 
    map.put("x-y-z","test-test1-test2");
    map.put("x1-y1-z1","test-test2-test3"); 
    

    Now I have an input string array that contains some piece of the key:

    String[] rem={"x","x1"}
    

    Based on this string array I want to remove HashMap values.

    Can anyone give an efficient approach to do this operation?