Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why map.keyset() returns set view but map.values() returns collections in Java?

This question is more about design implementation by Java developers. I want to know (if there any vital reason that I cannot think of) why Keyset() returns a set-view but values() returns Collection-view. why not return Values() as a ValueSet with set-view. I can cast to set if needed, but why it is chosen the way it is.

Maybe this could help in deciding what data structures to use when it comes to building our custom ones.

Map<String, Integer> map = new HashMap<String,Integer>();
map.put("hello",1);
map.put("world",2);

Collection <Integer> i = map.values();
Set<String> s = map.keySet();
like image 711
brain storm Avatar asked Jan 03 '14 21:01

brain storm


People also ask

What is map keyset() method in Java?

Map keySet () Method in Java with Examples Last Updated : 08 Sep, 2020 This method is used to return 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.

How to retrieve the key and value pairs of a map?

Map Interface is present in Java.util package, which provides mainly three methods KeySet (),entrySet () and values (). These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively.

What is the use of Map Key and value methods?

These methods are used to retrieve the keys of the map, key-value pairs of the map, and values of the map respectively. Since these methods are part of Map Interface, so we can use can these methods with all the classes implementing the map interface like TreeMap, HashMap, and LinkedHashMap.

Is map a collection in Java?

Answer: Although the map is viewed as a collection in general, it doesn’t implement a Collection interface. Some of the implementations of map, like treemap does not support null values or keys. Q #5) What is the difference between set and map?


1 Answers

By definition the keys of a Map form a Set, that is a collection of unique keys. The values of a Map can be duplicates however. So it is possible to have the same value for different keys in a Map.

like image 118
Meno Hochschild Avatar answered Oct 26 '22 23:10

Meno Hochschild