Saturday, June 29, 2019

java - Iterating over hashmap

The 'Map' data structure isn't a Collection object but Sets are.


The most common method to iterate over a Map is using the underlying .entrySet method.


// For each loop
for ( Entry entry : names ) {
System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
}
// Iterator
Iterator iterator = names.entrySet().iterator
while( iterator.hasNext() ){
Entry entry = iterator.next()
System.out.println( String.format( "(%s, %s)", entry.getKey(), entry.getValue() ) );
}

If are interested in finding the total number of Map nodes, use the .size() method.


EDIT:


Since you want the total size of each list stored within the map, you could do something like this.


Iterator iterator = names.entrySet().iterator
int count = 0;
while( iterator.hasNext() ){
Entry entry = iterator.next()
count += entry.getValue().size()
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...