CodeGym /Courses /New Java Syntax /What do we do with Set and Map?

What do we do with Set and Map?

New Java Syntax
Level 14 , Lesson 6
Available

"Not tired yet? Let's carry on, then. I'd like to give you more details about Set and Map and what they can do."

"Set is a set, a group of unnumbered objects. The main feature of a Set is that it only contains unique objects, i.e. each element of the set is different. Here are operations you can perform on a set:"

Operation Method
Add element(s) add(), addAll()
Remove element(s) remove(), removeAll()
Check for the presence of element(s) contains(), containsAll()

"And that's it?"

"Well, yes. You can also use the size() method to find out how many elements are in the set."

"What about Map?"

"Map is a set of pairs. It's like a Set, except it's a set of key-value pairs rather than unique elements. The only limitation is that each «key» must be unique. A Map can't contain two pairs with the same keys."

"Here's what we can do with Map:"

Operation Method
Get a set of all pairs entrySet()
Get a set of all keys keySet()
Get a set of all values values()
Add a pair put(key, value)
Get the value for the specified key get(key)
Check whether the specified key is present containsKey(key)
Check whether the specified value is present containsValue(value)
Check whether the Map is empty isEmpty()
Clear the Map clear()
Remove the value for the specified key remove(key)

"This is much more interesting than Set."

"Yes. Although Map isn't as popular as List, it is used in many tasks."

Comments (11)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Mrrobot993 Level 9, Italy
23 May 2023
ok
Fadhil Radhian Level 18, Semarang, Indonesia
27 March 2023
another simple and understandable explanation. Thanks
Sinisa Level 11, Banja Luka, Bosnia and Herzegovina
9 March 2021
This is third partial explanation of the same or very similar topics in this lesson.
Michal Level 9, Warsaw, Poland
2 March 2021
"Set is a set", ok, thx
NaeRae Level 11, United Kingdom
9 September 2021
Understandable,have a good day.
Jakub Góźdź Level 31, Katowice, Poland
13 February 2020
This explanation is so clear. Thank you.
5 January 2020
anyone noticed why the method is called values() for get all values and keySet() for all keys, not just keys()! i think, it's because map can only have unique keys, so they named it keySet. (java conventions!)
Onur Bal Level 27, Istanbul, Turkey
10 September 2020
Indeed. Since Sets can contain unique objects only, you can't return the values as a set, since there may be some repeating ones; whereas you can be sure that the keys, and the key-value pairs will be unique, hence the keySet() and entrySet() methods respectively.
Ifeanyi Level 31, Lagos, Nigeria
15 June 2019
got it!
Sergei Polakov Level 11, Donets'k, Ukraine
6 May 2019
good, ok, thanky!
Renat Mukhametshin Level 16, Pervouralsk, Russain Federation
29 April 2019
very interesting!