有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中HashMap的解析

我有一个简单的问题

我设定:

HashMap<A, B> myMap = new HashMap<A, B>();

...
myMap.put(...)
...

现在我想在myMap中循环并获取所有的键(类型A)。我该怎么做

我想通过循环从myMap中获取所有键,并将它们发送到“void myFunction(一个参数){…}”


共 (6) 个答案

  1. # 1 楼答案

    地图。keySet()将返回包含所有键的集。。从这里,您可以解析集合并获取所有密钥

  2. # 2 楼答案

    这是一个基于问题标题的更一般的答案

    解析键&;使用entrySet()的值

    HashMap<A, B> myMap = new HashMap<A, B>();
    
    ...
    myMap.put(key, value);
    ...
    
    for (Entry<A, B> e : myMap.entrySet()) {
        A key    = e.getKey();
        B value  = e.getValue();
    }
    
    //// or using an iterator:
    
    // retrieve a set of the entries
    Set<Entry<A, B>> entries = myMap.entrySet();
    // parse the set
    Iterator<Entry<A, B>> it = entries.iterator();
    while(it.hasNext()) {
        Entry<A, B> e = it.next();
        A key   = e.getKey();
        B value = e.getValue();
    }
    

    使用keySet()解析密钥

    HashMap<A, B> myMap = new HashMap<A, B>();
    
    ...
    myMap.put(key, value);
    ...
    
    for (A key   : myMap.keySet()) {
         B value = myMap.get(key);  //get() is less efficient 
    }                               //than above e.getValue()
    
    // for parsing using a Set.iterator see example above 
    

    有关问题Performance considerations for keySet() and entrySet() of MapentrySet()keySet()的更多详细信息,请参见

    使用values()解析值

    HashMap<A, B> myMap = new HashMap<A, B>();
    
    ...
    myMap.put(key, value);
    ...
    
    for (B value : myMap.values()) {
        ...
    }
    
    //// or using an iterator:
    
    // retrieve a collection of the values (type B)
    Collection<B> c = myMap.values();   
    // parse the collection
    Iterator<B> it = c.iterator();
    while(it.hasNext())
      B value = it.next();
    }
    
  3. # 3 楼答案

    我的地图。键集()?我不知道你到底是什么意思

  4. # 4 楼答案

    在将映射传递到您要将其传递到的任何地方之后,以映射结尾的方法/类将进行以下调用,以获取映射中的键集

    Set<A> keys = myMap.keySet();
    
  5. # 5 楼答案

    可以使用Google Guava来筛选集合。有关过滤、排序等的示例,请参见here

  6. # 6 楼答案

    以下是设置密钥的方法:

    Set<A> keys = myMap.keySet();
    

    我不知道“传承”是什么意思。我也不知道“解析”对HashMap意味着什么。除了把钥匙从地图上拿出来,这个问题毫无意义。投票结束