×

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

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Callable Statement in Java

The Callable statement in Java is used to call the functions and Stored procedures. Example: If we want to know about the age of a person based on their date of birth,...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

How to install Java in Windows 10

To make programs that can run on our systems, we need to install the programming language related software in our systems. Different programming language requires a different type of software aka...

6 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.