john
john

Reputation: 41

Get Set of entries from a Map

Given a map such as:

Map<String, Integer> = new Hashmap<String, Integer>;

How can I get a Collection<Integer> (any implementation of Collection would do) of the entrySet? Doing .entrySet() doesn't seem to work.

Upvotes: 3

Views: 13209

Answers (2)

hvgotcodes
hvgotcodes

Reputation: 120178

If you want to get just the map values you can use the values() method. The Javadoc page is here.

This is because your requirement is a Collection of Integers and the map values are of Integer type.

entrySet returns a collection of Map.Entry, each instance of which contains both the key and value that make up the entry, so if you want both the key and value, use entrySet() like so

Set<Map.Entry<String, Integer>> entries = map.entrySet()

Upvotes: 13

John B
John B

Reputation: 32949

That depends on if you truly want a SET. If you want a true Set you must do:

Set mySet = new HashSet(map.values());

Notice that values gives a Collection which can have duplicate entries.

Upvotes: 6

Related Questions