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();
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.
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.
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.
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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With