Ad space (banner)
โ˜•Java Lessons
Lesson 27 / 68

Working with HashSet (Sets)

This lesson covers handling data with no duplicates in Java using Set, so you understand the basics of the set data structure. It's for anyone searching "Java Set usage."

A Set is a "no-duplicates box" that can't hold the same value twice. It's handy for removing duplicates from an array, or quickly checking whether a value is present.

The example creates a Set from an array containing duplicates, {1, 2, 2, 3, 3, 3}, using new TreeSet<>(Arrays.asList(nums)) โ€” duplicates are automatically removed, and the order is sorted too. Notice checking for a value's presence with contains().

A common early mistake is not seeing the difference between HashSet and TreeSet. HashSet doesn't guarantee order, while TreeSet automatically keeps its elements sorted.

In real projects, a Set's contains() runs faster than a List's contains() on large amounts of data, making Set a genuinely convenient tool for deduplicating data.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)