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:
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:
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:
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:
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:
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:
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 –
- Layout in Java
- Java Compilers
- Java Parallel Stream
- 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!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment