Anurag Ramdasan
Anurag Ramdasan

Reputation: 4330

extracting values from HashMap

I was trying to learn and make understanding out of the working of a HashMap. So i created this hashmap to store certain values which upon displaying using an Iterator gives me outputs as

 1=2
 2=3
 3=4

and so on. This output i obtain using the Iterator.next() function. Now what my actual doubt is that since the type of this value returned in of an Iterator Object, if i need to extract only the right hand side values of the above equalities, is there any function for that? Something like a substring. Is there any way i could just get results as

 2
 3
 4

Any help will be appreciated. thanks in advance.

Upvotes: 6

Views: 25166

Answers (5)

ControlAltDel
ControlAltDel

Reputation: 35011

You are looking for map.values().

Upvotes: 3

Jonathan Payne
Jonathan Payne

Reputation: 2223

import java.util.HashMap;

public class Test
{
    public static void main( String args[] )
    {
        HashMap < Integer , Integer > map = new HashMap < Integer , Integer >();

        map.put( 1 , 2 );
        map.put( 2 , 3 );
        map.put( 3 , 4 );

        for ( Integer key : map.keySet() )
        {
            System.out.println( map.get( key ) );
        }
    }
}

Upvotes: 2

darrengorman
darrengorman

Reputation: 13116

You need the Map#values() method which returns a Collection.

You can then get an Iterator from this collection in the normal way.

Upvotes: 0

user949300
user949300

Reputation: 15729

Map has a method called values() to get a Collection of all the values. (the right side)

Likewise, there is a method call keySet() to get a Set of all the keys. (the left side)

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533492

I would use something like

Map<Integer, Integer> map = new HashMap<>();

for(int value: map.values())
   System.out.println(value);

Upvotes: 11

Related Questions