search
HomeJavajavaTutorialSet Interface in Java

Java provides an interface to store and manipulate data known as Collection Interface. The collection is the super interface for a Set interface that helps store any type of object and manipulate it. Set interface stands out as a Collection that does not allows duplicate data in it, i.e. if d1 and d2 are two data entries in the same Set, then the result of d1.equals(d2) should be false. Almost one null element is allowed in Set. Set models the mathematical set abstraction.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Some of the implementations of sets are HashedSet, LinkedHashSet, or TreeSet as sorted representation.

Examples to Implement Set Interface in Java

Below are the examples of Set Interface in Java:

1. HashSet

Code:

import java.util.*;
public class Main{
public static void main(String[] args)
{
// Set demonstration using HashSet
Set<integer> hash = new HashSet<integer>();
hash.add(1);
hash.add(4);
hash.add(1);
hash.add(3);
hash.add(2);
System.out.print("Set output without duplicates");
System.out.println(hash);
}
}</integer></integer>

Output:

Set Interface in Java

2. TreeSet

Code:

import java.util.*;
public class Main{
public static void main(String[] args)
{
// Set demonstration using TreeSet
Set<integer> tree = new TreeSet<integer>();
tree.add(1);
tree.add(4);
tree.add(1);
tree.add(3);
tree.add(2);
System.out.print("Set output without duplicates and sorted data "); System.out.println(tree);
}
}</integer></integer>

Output:

Set Interface in Java

Methods of Set Interface in Java

Methods supported by Set for various data object storage and manipulation.

  • add(Element e): Adds a specified element in the set.
  • addAll(Collection> c): Adds all the elements present in the specified collection.
  • clear(): Removes all the elements from the set.
  • contains(Object o): Returns true if Set contains the same object as the specified object.
  • containsAll(Collection> c): Returns true if set contains all of the elements in the specified collection.
  • size(): Returns the number of elements in the Set.
  • equals(Object o): It compares and returns true if our object is equal to the object specified.
  • hashCode(): It returns the hashcode value for the set.
  • isEmpty(): It returns true if the set contains no element.
  • iterator(): It returns an iterator on the set, which helps to trace through the complete set.
  • remove(Object o): Removes the specified element from the existing set.
  • removeAll(Collection> c): Removes the specified collection from the existing set.
  • toArray(): It returns the particular array containing all the elements as in Set.

Usage of methods in Our Code:

Code:

import java.util.LinkedHashSet;
public class Main
{
public static void main(String[] args)
{
LinkedHashSet<string> linked = new LinkedHashSet<string>();
// Adding element to LinkedHashSet
linked.add("Apple");
linked.add("Ball");
linked.add("Cat");
linked.add("Dog");
// Cannot add new element as Apple already exists
linked.add("Apple");
linked.add("Egg");
System.out.println("Size of LinkedHashSet: " + linked.size());
System.out.println("Old LinkedHashSet:" + linked);
System.out.println("Remove Dog from LinkedHashSet: " + linked.remove("Dog"));
System.out.println("Trying Remove Zoo which is not present "+ "present: " +        linked.remove("Zoo"));
System.out.println("Check if Apple is present=" + linked.contains("Apple"));
System.out.println("New LinkedHashSet: " + linked);
}
}</string></string>

Output:

Set Interface in Java

Converting HashSet to TreeSet

HashSet is generally used for search, delete and insert operations. HashSet is faster than TreeSet and uses a hash table. TreeSet whereas used for storing purpose due to its sorted data storage property. TreeSet uses TreeMap from the backend on Java. In order to store sorted data, insert elements into a hashmap and then insert data into a tree to get it sorted.

There are 3 ways to do this:

1. Pass the HashSet created

Code:

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Set<integer> hash = new HashSet<integer>();
hash.add(1);
hash.add(4);
hash.add(1);
hash.add(3);
hash.add(2);
System.out.print("HashSet");
System.out.println(hash);
//adding HashSet as a parameter to TreeSet constructor
Set treeSet = new TreeSet(hash);
// Print TreeSet
System.out.println("TreeSet: " + treeSet);
}
}</integer></integer>

Output:

Set Interface in Java

2. Using addAll() method

Code:

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Set<integer> hash = new HashSet<integer>();
hash.add(1);
hash.add(4);
hash.add(1);
hash.add(3);
hash.add(2);
System.out.print("HashSet");
System.out.println(hash);
//converting HashSet to TreeSet using addAll() method
Set<integer> treeSet = new TreeSet();
treeSet.addAll(hash);
// Print TreeSet
System.out.println("TreeSet: " + treeSet);
}
}</integer></integer></integer>

Output:

Set Interface in Java

3. Using for-each loop

Code:

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Set<integer> hash = new HashSet<integer>();
hash.add(1);
hash.add(4);
hash.add(1);
hash.add(3);
hash.add(2);
System.out.print("HashSet");
System.out.println(hash);
//converting HashSet to TreeSet using for each loop
Set<integer> treeSet = new TreeSet();
for (Integer i : hash)
{
treeSet.add(i);
}
// Print TreeSet
System.out.println("TreeSet: " + treeSet);
}
}</integer></integer></integer>

Output:

Set Interface in Java

Recommended Article

This is a guide to Set Interface in Java. Here we discuss the Introduction to Set Interface and how it is used to store and manipulate data in Java and its methods. You can also go through our other suggested articles to learn more –

  1. Layout in Java
  2. Java Compilers
  3. Java Parallel Stream
  4. Java BufferedReader

The above is the detailed content of Set Interface in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Java Platform Independent if then how?Is Java Platform Independent if then how?May 09, 2025 am 12:11 AM

Java is platform-independent because of its "write once, run everywhere" design philosophy, which relies on Java virtual machines (JVMs) and bytecode. 1) Java code is compiled into bytecode, interpreted by the JVM or compiled on the fly locally. 2) Pay attention to library dependencies, performance differences and environment configuration. 3) Using standard libraries, cross-platform testing and version management is the best practice to ensure platform independence.

The Truth About Java's Platform Independence: Is It Really That Simple?The Truth About Java's Platform Independence: Is It Really That Simple?May 09, 2025 am 12:10 AM

Java'splatformindependenceisnotsimple;itinvolvescomplexities.1)JVMcompatibilitymustbeensuredacrossplatforms.2)Nativelibrariesandsystemcallsneedcarefulhandling.3)Dependenciesandlibrariesrequirecross-platformcompatibility.4)Performanceoptimizationacros

Java Platform Independence: Advantages for web applicationsJava Platform Independence: Advantages for web applicationsMay 09, 2025 am 12:08 AM

Java'splatformindependencebenefitswebapplicationsbyallowingcodetorunonanysystemwithaJVM,simplifyingdeploymentandscaling.Itenables:1)easydeploymentacrossdifferentservers,2)seamlessscalingacrosscloudplatforms,and3)consistentdevelopmenttodeploymentproce

JVM Explained: A Comprehensive Guide to the Java Virtual MachineJVM Explained: A Comprehensive Guide to the Java Virtual MachineMay 09, 2025 am 12:04 AM

TheJVMistheruntimeenvironmentforexecutingJavabytecode,crucialforJava's"writeonce,runanywhere"capability.Itmanagesmemory,executesthreads,andensuressecurity,makingitessentialforJavadeveloperstounderstandforefficientandrobustapplicationdevelop

Key Features of Java: Why It Remains a Top Programming LanguageKey Features of Java: Why It Remains a Top Programming LanguageMay 09, 2025 am 12:04 AM

Javaremainsatopchoicefordevelopersduetoitsplatformindependence,object-orienteddesign,strongtyping,automaticmemorymanagement,andcomprehensivestandardlibrary.ThesefeaturesmakeJavaversatileandpowerful,suitableforawiderangeofapplications,despitesomechall

Java Platform Independence: What does it mean for developers?Java Platform Independence: What does it mean for developers?May 08, 2025 am 12:27 AM

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

How to set up JVM for first usage?How to set up JVM for first usage?May 08, 2025 am 12:21 AM

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

How can I check Java platform independence for my product?How can I check Java platform independence for my product?May 08, 2025 am 12:12 AM

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor