Saturday 29 June 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...