Menu

1 / 2

Set in Java – Simple Explanation

DEV Community·Jayashree·7 months ago
#Tpk5THgk
#beginners#dsa#java#tutorial#hashset
Reading 0:00
15s threshold

In Java, a Set is part of the Java Collections Framework and is used to store unique elements .

The main rule of Set:

No duplicate values allowed

What is a Set?

A Set is a collection that:

Does not allow duplicates

Does not maintain index

Can store null values (depends on implementation)

Types of Set in Java

1. HashSet

Does not maintain order

Fast performance

Allows one null value

HashSet < String > set = new HashSet <>(); set . add ( "Apple" ); set . add ( "Banana" ); set . add ( "Apple" ); // duplicate ignored

System . out . println ( set );

Enter fullscreen mode

Exit fullscreen mode

2. LinkedHashSet

Maintains insertion order

Slightly slower than HashSet

LinkedHashSet < String > set = new LinkedHashSet <>(); set . add ( "Apple" ); set . add ( "Banana" ); set . add ( "Mango" );

System . out . println ( set );

Enter fullscreen mode

Exit fullscreen mode

3. TreeSet

Stores elements in sorted order

Uses natural sorting

Does not allow null

TreeSet set = new TreeSet<>();

set .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.