Sets

  • Eclipse: Oxygen
  • Java: 1.8

The usage of sets is shown here. The sets are a unique type of data structure mostly used because it does not allow the repetition of the elements. The basic operations of sets are shown here.

In the following example, HashSet is created and elements are stored in the set using the add method.

HashSet does not contain the duplicate elements and it does not maintain any insertion order which means if we iterate into the set, it can return elements in any order.

Set does not return any individual value but, availability of element in a set can be verified using contains() method.

Contains() method return true, if the element is available in a set and it returns false if an element is unavailable in a set.

Output

Chaand

Mia

Armaan

John

Aafiya

chaand

false

Set types

The types of sets are shown here. They are linked set, hashed set and tree set. The difference between the three regarding the speed and insertion order is given.

In below table, we will see the properties of different types of Sets. HashSet uses the Hashing table, LinkedHashSet uses the Hashing table and LinkedList and TreeSet uses Tree for internal working.

In the following example, data is added to a HashSet and iterate through it using for each loop, no insertion order is maintained in output.

Output

A21

A22

A23

A24

A25

A26

A27

A28

A29

A1

A2

A3

A4

A5

A6

A7

A8

A9

A30

A10

A11

A12

A13

A14

A15

A16

A17

A18

A19

A20

In the following example, data is added to a LinkedHashSet and iterate through it using for each loop, insertion order is maintained in output.

Output

A30

A29

A28

A27

A26

A25

A24

A23

A22

A21

A20

A19

A18

A17

A16

A15

A14

A13

A12

A11

A10

A9

A8

A7

A6

A5

A4

A3

A2

A1

In the following example, data is added to a TreeSet and iterate through it using for each loop, data is sorted internally and displayed.

Output
A1

A10

A11

A12

A13

A14

A15

A16

A17

A18

A19

A2

A20

A21

A22

A23

A24

A25

A26

A27

A28

A29

A3

A30

A4

A5

A6

A7

A8

A9

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu