How to get the values from the Hashmap without using Iterator?

与世无争的帅哥 提交于 2019-12-21 23:52:20

问题


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.


回答1:


Map<String, Object> map = .....;//Initialization here
for (String key : map.keySet()) {
    // write your code here
}

//If you are just using keys of the 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




回答2:


Map.entrySet().stream().map(o -> o.getValue()).collect(Collectors.toList());




回答3:


for(String key : map.keySet()) {
   System.out.println("The key is: " + key + ",value is :" + map.get(key));
}

same result and iterator is gone =)




回答4:


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());

You can store it in variable as a string

String value = map.values().toString();

Hope this helps!



来源:https://stackoverflow.com/questions/29115392/how-to-get-the-values-from-the-hashmap-without-using-iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!