简体   繁体   中英

remove element from hash map if key is empty

how can I find an element of an HashMap in Java, if the HashMap is of the form and one key is empty, so it only contains a blank character.

In my example:

Let wordMap be an instance of HashMap filled with elements.

if (wordMap.containsKey("")) {
  wordMap.remove("");
}

This didn´t work. I hope someone can help me.

After I did this, I convert the hash map to a tree map and sort it by the biggest Integer. I print that to the console and this is what I get with

System.out.println("results: " + tree)

I get on the console:

results: { =194, in=73, ...}

Thanks

You can do a couple of different things. For your issue, I would do:

if (wordMap.containsKey(" ")) {
  wordMap.remove(" ");
}

However, to be more comprehensive I would iterate over the keys and remove any key that passes the StringUtils.isEmpty() test.

Are you trying to retrieve the value? If yes, then you need replace that wordMap.remove(""); with wordMap.get("");

Otherwise, if you're trying to remove the Entry with a key "" that is the correct way to do it.

If you are using Java 8, then you can apply the following solution.

    wordMap.entrySet()
       .removeIf(e -> StringUtils.isBlank(e.getKey()));

Here StringUtils.isBlank can be replaced with custom logic to check for invalid keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM