I was looking for a best way to loop through a map that involve as minimum resources as possible. Assume I have an object as the value, and the key is a string that referencing to the object. With the following two loop, may I know which one is better and how did you justified it run only minimum resources?
for(Map.Entry<String, MyObject> entry : myMap.entrySet()) {
...
}
for( String key : myMap.keySet() ) {
...
}
THanks @!
This depends on which specific
Mapyou use. It’s impossible to tell as it stands, sinceMapis an interface.In most map implementations both
entrySetandkeySetwill return a view of the underlying set of entries / keys, so I’d say that they are likely more or less as efficient in all aspects.Note that if you retrieve all entries you’re getting the values at the same time. This may save you some time if you often need the value.