Java 如何在不使用迭代器的情况下从 Hashmap 中获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29115392/
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
How to get the values from the Hashmap without using Iterator?
提问by B Narasimha
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue());
}
This is my code. Now i don't want to use Iterator to get the values. Please help me to find best solution.
这是我的代码。现在我不想使用 Iterator 来获取值。请帮助我找到最佳解决方案。
采纳答案by Rishi
Map<String, Object> map = .....;//Initialization here
for (String key : map.keySet()) {
// write your code here
}
//If you are just using keys of the Map
//如果你只是使用Map的键
for (Object value : map.values()) {
// write your code here
}
//If you are just using values from your Map
//如果您只是使用地图中的值
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// you code here
}
//If you want both Keys and values
//如果你想要键和值
//All are without using Iterator of the Map
//所有都没有使用Map的Iterator
回答by owenrb
for(String key : map.keySet()) {
System.out.println("The key is: " + key + ",value is :" + map.get(key));
}
same result and iterator is gone =)
相同的结果和迭代器消失了 =)
回答by alcatraz
Map.entrySet().stream().map(o -> o.getValue()).collect(Collectors.toList());
Map.entrySet().stream().map(o -> o.getValue()).collect(Collectors.toList());
回答by Madhav Saraf
If you want to print all the values without using loop or iterator from map you can do like this
如果你想在不使用循环或迭代器的情况下打印所有值,你可以这样做
Map <Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Hello");
map.put(2, "Welcome");
System.out.println(map.values().toString());
Map <Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Hello");
map.put(2, "Welcome");
System.out.println(map.values().toString());
You can store it in variable as a string
您可以将其作为字符串存储在变量中
String value = map.values().toString();
String value = map.values().toString();
Hope this helps!
希望这可以帮助!