java 从 HashMap 中提取值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10180214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:57:37  来源:igfitidea点击:

extracting values from HashMap

javaiteratorhashmap

提问by Anurag Ramdasan

I was trying to learn and make understanding out of the working of a HashMap. So i created this hashmap to store certain values which upon displaying using an Iterator gives me outputs as

我试图从 HashMap 的工作中学习和理解。所以我创建了这个哈希图来存储某些值,这些值在使用迭代器显示时给我输出

 1=2
 2=3
 3=4

and so on. This output i obtain using the Iterator.next()function. Now what my actual doubt is that since the type of this value returned in of an Iterator Object, if i need to extract only the right hand side values of the above equalities, is there any function for that? Something like a substring. Is there any way i could just get results as

等等。我使用该Iterator.next()函数获得的这个输出。现在我真正的疑问是,由于这个值的类型是在迭代器对象中返回的,如果我只需要提取上述等式的右侧值,是否有任何函数?类似子串的东西。有什么办法可以让我得到结果

 2
 3
 4

Any help will be appreciated. thanks in advance.

任何帮助将不胜感激。提前致谢。

回答by Peter Lawrey

I would use something like

我会使用类似的东西

Map<Integer, Integer> map = new HashMap<>();

for(int value: map.values())
   System.out.println(value);

回答by ControlAltDel

You are looking for map.values().

您正在寻找map.values().

回答by user949300

Map has a method called values() to get a Collection of all the values. (the right side)

Map 有一个叫做 values() 的方法来获取所有值的集合。(右侧)

Likewise, there is a method call keySet() to get a Set of all the keys. (the left side)

同样,有一个方法调用 keySet() 来获取所有键的 Set。(左侧)

回答by Jonathan Payne

import java.util.HashMap;

public class Test
{
    public static void main( String args[] )
    {
        HashMap < Integer , Integer > map = new HashMap < Integer , Integer >();

        map.put( 1 , 2 );
        map.put( 2 , 3 );
        map.put( 3 , 4 );

        for ( Integer key : map.keySet() )
        {
            System.out.println( map.get( key ) );
        }
    }
}

回答by darrengorman

You need the Map#values()method which returns a Collection.

您需要Map#values()方法返回一个Collection.

You can then get an Iteratorfrom this collection in the normal way.

然后,您可以Iterator以正常方式从该集合中获取。