Java HashSet is an unordered and no-duplicate elements collection, implementation of the java.util.Set interface and is a part of the Java Collections Framework

HashSet has the following attributes

  • Backed by hash table data structure (actually a HashMap instance)

  • No guarantees to the iteration order

  • Contains no duplicate elements, at most one null element

  • Offers constant time performance for add, remove, contains and size operations, assuming the hash function distributes the elements properly among the buckets

  • Unsynchronized implementation. In multi-threading environment with at least one thread modifies the list, it must be synchronized externally

The below examples give you some basic usages of HashSet




You can learn using HashSet in more details with these tutorials

  • Create and Initialize an HashSet by using its constructors, add(Object) and addAll(Collection) methods

  • Iterate a HashSet by using iterator, for-each loop and Java 8+ forEach(Consumer) method of Iterable interfaces

  • Query a HashSet including find elements / objects, check if existing elements / objects and query the size of a HashSet

  • Modify a HashSet by using remove and add methods to remove and update elements / objects in a HashSet

  • Sort a HashSet by using TreeSet, ArrayList instance's sort(Comparator), Collections.sort(List) or Collections.sort(List, Comparator) methods in conjunction with Comparable and Comparator interfaces to control over the sort order