Is there any way to iterate through a java Hashmap and print out all the values for every key that is a part of the Hashmap?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Java 8 added
Map.forEach
which you can use like this:There's also
replaceAll
if you want to update the values:Yes, you do this by getting the
entrySet()
of the map. For example:(Ofcourse, replace
String
andObject
with the types that your particularMap
has - the code above is just an example).use a
for
loop to iterate it.then use
hashmap.get(item)
to get individual values,Alternatively just use
entrySet()
for getting an iterator for values.In addition, if you use a LinkedHashMap as the implementation, you'll iterate in the order the key/value pairs were inserted. If that's not important, use a HashMap.
With for-each loop, use
Map.keySet()
for iterating keys,Map.values()
for iterating values andMap.entrySet()
for iterating key/value pairs.Note that all these are direct views to the map that was used to acquire them so any modification you make to any of the three or the map itself will reflect to all the others too.