×

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

Sort Elements by Frequency in Java

To sort the elements in Java by using frequency, we need an input array. We should create a function that sorts the elements in an array by using their frequencies...

3 minutes read.

Java Integer doubleValue() method

The doubleValue() method of Integer class returns a double value for this Integer after a widening primitive conversion. Syntax public double doubleValue() Parameters NA Specified by This method is specified by doubleValue in class Number Return Value This...

1 minute read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Stack Program in Java

Stack Program in Java The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector...

5 minutes read.

How to Convert Date to String in Java

How to Convert Date to String in Java We need to convert Date to String in Java may for displaying purpose. We can convert Date to String in Java using the format() method of java.text.DateFormat class. There...

2 minutes read.

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that...

2 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Java BufferedWriter

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

Even Odd Program in Java

Even Odd Program in Java The number that are completely divisible by 2 are even and the number that leaves remainder are odd numbers. For example, the numbers 2, 0, 4,...

5 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Camel Case in Java

Java names its classes, interfaces, methods, as well as variables using camel-case syntax. If the name consists of two words, the second word will always begin with a capital letter,...

3 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Buffered Writer

BufferWriter Class: It is used to write the data more efficiently. This class is present in the java.io package, it inherits the data from the Writer class. Writer class is...

4 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.