0% found this document useful (0 votes)
11 views

Java Set Interface

A set is an interface that helps store unique elements without duplicates. It has classes like HashSet, LinkedHashSet, TreeSet that implement the set interface. Sets allow basic operations like union, intersection, difference on elements. Common set methods include add(), addAll(), clear(), contains(), containsAll() and more.

Uploaded by

antimbhowal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Set Interface

A set is an interface that helps store unique elements without duplicates. It has classes like HashSet, LinkedHashSet, TreeSet that implement the set interface. Sets allow basic operations like union, intersection, difference on elements. Common set methods include add(), addAll(), clear(), contains(), containsAll() and more.

Uploaded by

antimbhowal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

JAVA SET INTERFACE

A set is an interface of Java collections that helps in storing and processing


of elements.
➔ It is an ordered/unordered collection.
➔ It has no guarantee that the elements will be ordered.
➔ It cannot contain duplicate values.
➔ It allows at most one null value.
List has the following classes:
➔ HashSet - HashSet class implements Set Interface. It represents the
collection that uses a hash table for storage. Hashing is used to store
the elements in the HashSet. It contains unique items.
➔ LinkedHashSet - LinkedHashSet class represents the LinkedList
implementation of Set Interface. It extends the HashSet class and
implements Set interface. Like HashSet, It also contains unique
elements. It maintains the insertion order and permits null elements.
➔ SortedSet - SortedSet is the alternate of Set interface that provides a
total ordering on its elements. The elements of the SortedSet are
arranged in the increasing (ascending) order. The SortedSet provides
the additional methods that inhibit the natural ordering of the
elements.
➔ Enumset - An enumSet is a Java Collections member, it is not
synchronized. An enumSet is a high performing set implementation
that works faster than the HashSet. All the elements in an enumSet
must be of a single enumeration type that is specified when the set is
created.
➔ TreeSet - Java TreeSet class implements the Set interface that uses
a tree for storage. Like HashSet, TreeSet also contains unique
elements. However, the access and retrieval time of TreeSet is quite
fast. The elements in TreeSet stored in ascending order.

How to create a set


1. Set<data-type> s1 = new HashSet<data-type>();
2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

4. SortedSet<data-type> set = new TreeSet();

Operations on the Set Interface


On the Set, we can perform all the basic mathematical operations like
intersection, union and difference.
Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and
set2 = [33, 2, 83, 45, 3, 12, 55]. We can perform the following operation on
the Set:

o Intersection: The intersection operation returns all those elements


which are present in both the set. The intersection of set1 and set2
will be [33, 45, 55].
o Union: The union operation returns all the elements of set1 and set2
in a single set, and that set can either be set1 or set2. The union of
set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83].
o Difference: The difference operation deletes the values from the set
which are present in another set. The difference of the set1 and set2
will be [66, 34, 22, 77].

In set, addAll() method is used to perform the union, retainAll() method is


used to perform the intersection and removeAll() method is used to
perform difference. Let's take an example to understand how these
methods are used to perform the intersection, union, and difference
operations.

import java.util.*;
public class SetOperations
{
public static void main(String args[])
{
Integer[] A = {22, 45,33, 66, 55, 34, 77};
Integer[] B = {33, 2, 83, 45, 3, 12, 55};
Set<Integer> set1 = new HashSet<Integer>();
set1.addAll(Arrays.asList(A));
Set<Integer> set2 = new HashSet<Integer>();
set2.addAll(Arrays.asList(B));

// Finding Union of set1 and set2


Set<Integer> union_data = new HashSet<Integer>(set1);
union_data.addAll(set2);
System.out.print("Union of set1 and set2 is:");
System.out.println(union_data);

// Finding Intersection of set1 and set2


Set<Integer> intersection_data = new HashSet<Integer>(set1);
intersection_data.retainAll(set2);
System.out.print("Intersection of set1 and set2 is:");
System.out.println(intersection_data);

// Finding Difference of set1 and set2


Set<Integer> difference_data = new HashSet<Integer>(set1);
difference_data.removeAll(set2);
System.out.print("Difference of set1 and set2 is:");
System.out.println(difference_data);
}
}
Output:

Basic Set programs


Add() method:
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }
Output:
Vijay
Ravi
Ajay

Addall() method:
The addAll() method appends all the elements of the specified collection to
the set.
import java.io.*;
import java.util.*;
class addAllMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
System.out.println("Set: " + data);
ArrayList<Integer> newData = new ArrayList<Integer>();
newData.add(91);
newData.add(71);
newData.add(81);
data.addAll(newData);
System.out.println("Set: " + data);
} }
Output:

Clear () method: The method removes all the elements from the set. It
doesn't delete the reference of the set. It only deletes the elements of
the set.

import java.io.*;
import java.util.*;
public class clearMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();

data.add(31);
data.add(21);
data.add(41);
System.out.println("Set: " + data);

data.clear();
System.out.println("The final set: " + data);
}
}

Output:
Contains() method: The contains() method is used to know the presence of
an element in the set. Its return value is true or false depending on the
presence of the element.

import java.io.*;
import java.util.*;
class containsMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(51);
data.add(11);
data.add(81);
System.out.println("Set: " + data);
System.out.println("Does the Set contains '91'?" + data.contains(91
));
System.out.println("Does the Set contains 'javaTpoint'? " + data.con
tains("4"));
System.out.println("Does the Set contains '51'? " + data.contains(5
1));
}
}
Output:

5) containsAll()
The method is used to check whether all the elements of the collection are
available in the existing set or not. It returns true if all the elements of the
collection are present in the set and returns false even if one of the elements
is missing in the existing set.
Syntax:
1. public boolean containsAll(Collection data)
SetExample7.java
import java.io.*;
import java.util.*;
class containsAllMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(51);
data.add(11);
data.add(81);

System.out.println("data: " + data);

Set<Integer> newData = new LinkedHashSet<Integer>();


newData.add(31);
newData.add(21);
newData.add(41);

System.out.println("\nDoes data contains newData?: "+ data.contain


sAll(newData));

} }
Output:

6) hashCode()
The method is used to derive the hash code value for the current instance of
the set. It returns hash code value of integer type.
Syntax:
1. public int hashCode()
SetExample8.java
import java.io.*;
import java.util.*;
class hashCodeMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(51);
data.add(11);
data.add(81);
System.out.println("data: " + data);
System.out.println("\nThe hash code value of set is:"+ data.hashCo
de());
}
}
Output:
7) isEmpty()
The isEmpty() method is used to identify the emptiness of the set . It returns
true if the set is empty and returns false if the set is not empty.
Syntax:
1. boolean isEmpty()
SetExample9.java
import java.io.*;
import java.util.*;
class isEmptyMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(51);
data.add(11);
data.add(81);
System.out.println("data: " + data);
System.out.println("\nIs data empty?: "+ data.isEmpty());
}
}
Output:
8) iterator()
The iterator() method is used to find the iterator of the set. The iterator is
used to get the element one by one.
Syntax:
1. Iterator iterate_value = set1.iterator();
SetExample10.java
import java.io.*;
import java.util.*;
class iteratorMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(51);
data.add(11);
data.add(81);
System.out.println("data: " + data);
Iterator newData = data.iterator();
System.out.println("The NewData values are: ");
while (newData.hasNext()) {
System.out.println(newData.next());
}
}
}
Output:

9) remove()
The method is used to remove a specified element from the Set. Its return
value depends on the availability of the element. It returns true if the element
is available in the set and returns false if it is unavailable in the set.
Syntax:
1. boolean remove(Object O)
SetExample11.java
import java.io.*;
import java.util.*;
class removeMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(51);
data.add(11);
data.add(81);
System.out.println("data: " + data);

data.remove(81);
data.remove(21);
data.remove(11);
System.out.println("data after removing elements: " + data);
}
}
Output:

11) removeAll()
The method removes all the elements of the existing set from the specified
collection.
Syntax:
1. public boolean removeAll(Collection data)
SetExample12.java
import java.io.*;
import java.util.*;
class removeAllMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(91);
data.add(71);
data.add(81);
System.out.println("data: " + data);

ArrayList<Integer> newData = new ArrayList<Integer>();


newData.add(91);
newData.add(71);
newData.add(81);
System.out.println("NewData: " + newData);

data.removeAll(newData);
System.out.println("data after removing Newdata elements : " + dat
a);
}
}
Output:

11) retainAll()
The method retains all the elements from the set specified in the given
collection.
Syntax:
1. public boolean retainAll(Collection data)
SetExample13.java
import java.io.*;
import java.util.*;
class retainAllMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(91);
data.add(71);
data.add(81);
System.out.println("data: " + data);

ArrayList<Integer> newData = new ArrayList<Integer>();


newData.add(91);
newData.add(71);
newData.add(81);
System.out.println("newData: " + newData);

data.retainAll(newData);
System.out.println("data after retaining newdata elements : " + data
);
}
}
Output:

12) size()
The method returns the size of the set.
Syntax:
1. int size()
SetExample14.java
import java.io.*;
import java.util.*;
class sizeMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(91);
data.add(71);
data.add(81);
System.out.println("data: " + data);

System.out.println("size of the data is : " + data.size());


}
}
Output:

13) removeAll()
The method is used to create an array with the same elements of the set.
Syntax:
1. Object[] toArray()
SetExample15.java
import java.io.*;
import java.util.*;
class toArrayMethod {
public static void main(String args[])
{
Set<Integer> data = new LinkedHashSet<Integer>();
data.add(31);
data.add(21);
data.add(41);
data.add(91);
data.add(71);
data.add(81);
System.out.println("data: " + data);

Object[] array_data = data.toArray();


System.out.println("The array is:");
for (int i = 0; i < array_data.length; i++)
System.out.println(array_data[i]);
}
}
Output:

You might also like