I have been wondering about the Map from java.util.
Why does values() method return a Collection while the keySet and entrySet return a Set?
What's the advantages/disadvantages of a Set and Collection?
A set guarantees that a given entry can only exist in it once. A Collection doesn't. Since a Map has no uniqueness guarantees in terms of values, the set of them isn't really a set at all but would have to be a Collection.
It's not really an issue of advantages and disadvantages -- it's what the keys, values and entries of a map represent that's important.
Keys in a map are unique
The keys in a Map are unique -- that is, there aren't going to be duplicate keys in a Map. A Collection which assures that duplicates don't exist is a Set.
Therefore, the keys are returned as a Set by the keySet method.
Values in a map are not necessarily unique
On the other hand, the values of a Map does not have to be unique.
For example, we could have an entry in a map with the key "fruit" map to the value "apple", and also have another entry with key "computer" mapping to the value "apple":
map {
key:"fruit" -> value:"apple"
key:"computer" -> value:"apple"
}
Having duplicate values in a map is allowed.
Therefore, we cannot use a Set, as that necessitates that all the entries unique. A good choice for the values of a Map is to return a plain-old Collection as it does not impose any restrictions to what the values are.
Entries in a map are also unique
The entries of the Map are unique -- they are a combination of the key and value, represented by the Map.Entry object. Since this key-value pair is unique, it is returned as a Set by the entrySet method.
Further reading
Map internally manages Set of keys because keys are unique values aren't
Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
Also See
Bagtype, this would be more appropriate here.