简体   繁体   English

如果键为空,则从哈希映射中删除元素

[英]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. 如果HashMap的形式和一个键为空,那么如何在Java中查找HashMap的元素,因此它仅包含一个空白字符。

In my example: 在我的示例中:

Let wordMap be an instance of HashMap filled with elements. 令wordMap为填充有元素的HashMap的实例。

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. 但是,为了更全面,我将遍历键并删除任何通过StringUtils.isEmpty()测试的键。

Are you trying to retrieve the value? 您是否要检索值? If yes, then you need replace that wordMap.remove(""); 如果是,那么您需要替换该wordMap.remove(“”); with wordMap.get(""); 与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. 如果您使用的是Java 8,则可以应用以下解决方案。

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

Here StringUtils.isBlank can be replaced with custom logic to check for invalid keys. 在这里, StringUtils.isBlank可以用自定义逻辑替换,以检查无效密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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