×

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 Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Java 8 Features

Java 8 Features: After the great success of Java 7, many developers were waiting for the next version of one of the best languages in the tech world. Moreover, on...

6 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

How to Calculate Week Number From Current Date in Java?

The WeekFields class's weekOfMonth() method is utilized to return the field for access the week of a month based on this WeekFields. If the first day of the month is a...

3 minutes read.

How to get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Java Math decrementExact() Method

The decrementExact() method of Math class returns the argument which is decremented by one, throwing an exception is the result overflows an int or long. Syntax: public static int decrementExact (int a) Parameters: The...

1 minute read.

How to sort a String in Java

Sorting is the process of putting the elements in a certain order, either ascending or descending. Mostly the alphabetical order or natural order is used for a string. In other...

5 minutes read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.