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!

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.

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

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

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

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

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

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.

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


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

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

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
The most popular open source editor
