【问题标题】:Remove items from HashMap by key in java在java中通过键从HashMap中删除项目
【发布时间】:2015-11-06 15:10:03
【问题描述】:

我有一个这样的 HashMap

public static HashMap<String, Integer> jsonPosition = new HashMap<String, Integer>();

我在我的 hashmap 中放了一些这样的值

GlobalClassParameters.jsonPosition.put("another income",
                        GlobalClassParameters.jsonPosition.size());

现在我想通过它们的键删除项目。我写了一些代码,可以删除键等于某个值的所有项目。

Object objectToRemove = null;
Iterator<Map.Entry<String, Integer>> iter = GlobalClassParameters.jsonPosition.entrySet().iterator();

while (iter.hasNext()) {
   Map.Entry<String, Integer> entry = iter.next();

   if(entry.getKey().equalsIgnoreCase("another income"))
   {
      objectToRemove = entry;
      break;
   }  
}                               

if(objectToRemove != null)
{
   GlobalClassParameters.jsonPosition.entrySet().remove(objectToRemove);
}

我的问题是我不需要删除所有键等于我的“另一个收入”的对象,但我只想删除一个具有该键的对象。

【问题讨论】:

  • 你要删除哪一个?
  • 是的,只有一个对象@Rohit5k2
  • 像HashMap 这样的Map 对于每个键只有一个 值。删除键时,会删除关联的值。如果你想要更多,你应该使用MultiMap。
  • 在我知道尝试清理您的问题之后,我理解了您的问题。由于 hashmaps 保存键值对,每个键只有一个值,因此键“Another Income”根本不可能有多个整数。

标签: java android dictionary hashmap


【解决方案1】:

您不能在 HashMap 中为单个键放置多个值。您只是覆盖了此键的先前值。

除了 Maps 确实有一个 remove 方法,它接受一个键并删除该键的条目。

【讨论】:

    【解决方案2】:

    Java 中的 HashMap 每个键只保存一个值。

    "Income"           => 4500
    "Another Income"   => 6700
    "Third Income"     => 2400
    

    因此,如果您要求 HashMap 删除键“Another Incomse”后面的整数,则只有一个值被删除。

    HashMap 无法实现以下目标!!

    "Income"           => 4500
    "Another Income"   => 6700
    "Another Income"   => 5300
    "Third Income"     => 2400
    

    使用此代码

    HashMap<String, Integer> incomes = new HashMap<String, Integer>();
    incomes.put("Income", 4500);
    incomes.put("Another Income", 6700);
    incomes.put("Another Income", 5300);
    incomes.put("Third Income", 2400);
    

    将导致:

    "Income"           => 4500
    "Another Income"   => 5300
    "Third Income"     => 2400
    

    自从您第二次为“Another Income”分配一个值后,您只需覆盖您的第一个条目。

    【讨论】:

    • 我用“Another Incomse”键放置了一些对象,当我删除“Another Incomse”然后打印我的hashmap--hashmap为空
    • 是的,因为每次为键“Another Income”输入一个整数时,都会覆盖该键的任何现有整数。每个键只能有一个值,这就是 HashMap(或一般的映射)在 Java 中的工作方式。
    • 什么是解决方案?你能给我看一些例子吗,或者你是否可以重写我的代码。谢谢
    • 如果您甚至不告诉我们您要达到的目标,我该如何帮助您?!告诉我们您想做什么,我们可以帮助您。你为什么选择哈希图?你的软件是做什么用的?
    • 我尝试向您解释我的问题。我有一些列表。在列表中单击我按位置删除列表中的项目(例如,我在列表中有 4 个项目,这意味着我放置了“AnotherIncom”对象在我的哈希图中),如果我删除了列表中的一些值,还想在我的哈希图中删除一个“AnotherIncome”键对象。
    猜你喜欢
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多