×

Java Set Interface

We use set when we don't want to allow duplicate entries. All Set implementations do not allow duplicates.

  • HashSet: This class stores its elements in hash tables. It uses the hashCode() method to find the objects. This class has the benefit that addition and checking the presence of an element has constant time. The disadvantage is that we lose the order of insertion of the elements.
  • LinkedHashSet: Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits the HashSet class and implements the Set interface.
  • TreeSet: This class stores its elements in a sorted tree structure. The benefit is that elements are always in sorted order, but addition and checking the presence of an element takes longer time O(log n). TreeSet implements a special interface called NavigableSet.

Useful Methods

Modifier and Type

Method

Description

boolean

add(E e)

It adds the specified element to this set if it is not already present (optional operation).

boolean

addAll(Collection<? extends E> c)

It adds all of the elements in the specified collection to this set if they're not already present (optional operation).

void

clear()

It removes all of the elements from this set (optional operation).

boolean

contains(Object o)

It returns true if this set contains the specified element.

boolean

remove(Object o)

It removes the specified element from this set if it is present (optional operation).

boolean

equals(Object o)

It compares the specified object with this set for equality.

int

hashCode()

It returns the hash code value for this set.

boolean

isEmpty()

It returns true if this set contains no elements.

Iterator<E>

iterator()

It returns an iterator over the elements in this set.

Example: HashSet

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class SetExample {
public static void main(String[] args) {
Set<String> setType = new HashSet<String>();
setType.add("INDIA");
setType.add("CHINA");
setType.add("PAKISTAN");
// access via Iterator
Iterator<String> iterator = setType.iterator();
while (iterator.hasNext()) {
String element = (String) iterator.next();
System.out.println(element);
}
}
}

Output:

CHINA
PAKISTAN
INDIA

Example: LinkedHashSet

import java.util.LinkedHashSet;

public class MyClass {
public static void main(String[] args) {
LinkedHashSet<Integer> linkedset = new LinkedHashSet<Integer>();
// Adding element to LinkedHashSet
linkedset.add(10);
linkedset.add(40);
linkedset.add(30);
linkedset.add(20);
// This will not add new element as 40 already exists
linkedset.add(40);
linkedset.add(11);
System.out.println("Size of LinkedHashSet = " + linkedset.size());
System.out.println("Original LinkedHashSet:" + linkedset);
System.out.println("Removing 10 from LinkedHashSet: " + linkedset.remove(10));
System.out.println("Trying to Remove 100 which is not " + "present: " + linkedset.remove(100));
System.out.println("Checking if 30 is present=" + linkedset.contains(30));
System.out.println("Updated LinkedHashSet: " + linkedset);
}
}
Output:
Size of LinkedHashSet = 5
Original LinkedHashSet:[10, 40, 30, 20, 11]
Removing 10 from LinkedHashSet: true
Trying to Remove 100 which is not present: false
Checking if 30 is present=true
Updated LinkedHashSet: [40, 30, 20, 11]

Example: TreeSet

import java.util.TreeSet;
public class MyClass {
public static void main(String[] args) {
        TreeSet<Integer> treeSet= new TreeSet<>();
        treeSet.add(100);
        treeSet.add(50);
        treeSet.add(200);
        // Duplicates will not get insert
        treeSet.add(50);
        // Elements get stored in default natural
        // Sorting Order(Ascending)
        System.out.println(treeSet);  // [50,100,200]
        // ts1.add("Abc") ; will throw ClassCastException at run time
}
}

Output:

[50, 100, 200]

Related Topics

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Program to Find the Common Elements between two Arrays in Java

In this article, we are going to learn how to find the common elements between two arrays using Java. Here, we use different approaches in Java to find the common...

3 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

IdentityHashMap in Java

The IdentityHashMap class is comparable to the HashMap class and is an AbstractMap implementation. However, when comparing the key, it uses reference equality rather than object equality (or values). Identity HashMap...

6 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

Caesar Cipher Program in Java

It is among the most popular and straightforward encryption methods. With this method, each letter in the text is swapped out for a letter that is a certain number of...

3 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Bubble Sort in Java

Bubble Sort in Java Bubble sort isalso known as sinking sort. It is one of the simplest sorting algorithms. In the bubble sort algorithm, the given array is traversed from left...

5 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Checked vs Unchecked Exceptions in Java

In this tutorial, we will discuss Java's checked and unchecked Exceptions. Exception An exception is an undesirable event that disrupts the normal flow of the program. An exception is thrown at runtime. It...

4 minutes read.