Ankit Duggal
Ankit Duggal

Reputation: 55

Remove Entries in hashmap using composite String key

I have hashmap Key is String composed of concatenation of 3 elements (element1+element2+element3)

String key=element1+element2+element3;

which is put in the hashmap

HashMap<String,Object> map=new Hashmap<String,Object>();
map.put(key,new Object());

i want to remove all the entries in the hashmap matching key having element2 if(key.contains("element2")) then remove that entry in hashmap.

How accomplish this?

Upvotes: 0

Views: 2542

Answers (4)

Justinas Jakavonis
Justinas Jakavonis

Reputation: 8838

Simple way is to get keySet() from your map which

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.

So

yourMap.keySet().removeIf(key -> key.contains(keyPart));

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

Hash map needs an exact key - accessing by a partial key is not possible, meaning that you would need to iterate all keys, check for match on "element2", and remove elements as you go:

Iterator<Map.Entry<String,Object>> iter = map.entrySet().iterator();
while(iter.hasNext()){
     Map.Entry<String,Object> entry = iter.next();
     if (entry.key().contains("element2")) {
         iter.remove();
     }
}

Upvotes: 5

Sultan
Sultan

Reputation: 71

we could also use Pattern and Matcher functionality

    public class TestMatcher {

        public static void main(String[] args) {

            Map<String, Integer> sampleData = new HashMap<String, Integer>();
            sampleData.put("data1data21data3", new Integer(1));
            sampleData.put("data1data2A", new Integer(1));
            sampleData.put("data1data3", new Integer(1));
            sampleData.put("data3", new Integer(1));

            TestMatcher tm = new TestMatcher();
            tm.printMatchKey("data2[A-Z0-9]{1}", sampleData);
        }

        public void printMatchKey(String regex, Map<String, Integer> data) {
            Pattern pattern = Pattern.compile(regex);

            Iterator<String> keyIterator = data.keySet().iterator();
            while(keyIterator.hasNext()) {
                String key = keyIterator.next();
                Matcher matcher = pattern.matcher(key);
                if (matcher.find()) {
                    System.out.println("Key " + key + " contains " + regex);
                }
            }
        }
    }

Related to this.

Upvotes: 2

Sumeet Sharma
Sumeet Sharma

Reputation: 2583

Have a look at this.. A regex map which has regular expressions as its key so you wont need to iterate through all key value pairs yourself .. its a custom map implementation..

Check Here

Upvotes: 0

Related Questions