Set in Java
The set interface is present in java.util package
extends the Collection interface
an unordered collection of objects
duplicate values cannot be stored
an interface that implements the mathematical set.
interface contains the methods inherited from the Collection interface
adds a feature that restricts the insertion of the duplicate elements.
Creating Set Objects
Since Set is an interface, We always need a class that extends this list in order to create an
object.
In order to use functionalities of the Set interface, we can use these classes:
HashSet
LinkedHashSet
EnumSet
TreeSet
Set<Obj> set = new HashSet<Obj> ();
Methods:
add(element)
addAll(collection)
clear()
contains(element)
containsAll(collection)
isEmpty()
iterator()
remove(element)
removeAll(collection)
size()
Example:
Set<String> hash_Set = new HashSet<String>();
// Adding elements to the Set
hash_Set.add("Geeks");
hash_Set.add("For");
hash_Set.add("Geeks");
hash_Set.add("Example");
hash_Set.add("Set");
// Printing elements of HashSet object
System.out.println(hash_Set);
Output
[Set, Example, Geeks, For]
Operations on the Sets
Let set1 = [1, 3, 2, 4, 8, 9, 0] and set2 = [1, 3, 7, 5, 4, 0, 7, 5].
Intersection = [0, 1, 3, 4]
Union = [0, 1, 2, 3, 4, 5, 7, 8, 9]
Difference = [2, 8, 9]
Example:
Set<Integer> a = new HashSet<Integer>();
a.addAll(Arrays.asList(new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));
Set<Integer> b = new HashSet<Integer>();
b.addAll(Arrays.asList(new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));
// To find union
Set<Integer> union = new HashSet<Integer>(a);
union.addAll(b);
System.out.print("Union of the two Set");
System.out.println(union);
// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
intersection.retainAll(b);
System.out.print("Intersection of the two Set");
System.out.println(intersection);
// To find the symmetric difference
Set<Integer> difference = new HashSet<Integer>(a);
difference.removeAll(b);
System.out.print("Difference of the two Set");
System.out.println(difference);
Performing Various Operations on SortedSet
Adding Elements
Set<String> hs = new HashSet<String>();
// Adding elements to above object
// using add() method
hs.add("B");
hs.add("B");
hs.add("C");
hs.add("A");
// Printing the elements inside the Set object
System.out.println(hs);
Accessing the Elements
String check = "D";
// Check if the above string exists in
// the SortedSet or not
// using contains() method
System.out.println("Contains " + check + " "+ hs.contains(check));
Removing the Values
hs.remove("B");
// Printing Set elements after removing an element
// and printing updated Set elements
System.out.println("After removing element " + hs);
Iterating through the Set
for (String value : hs)
// Printing all the values inside the object
System.out.print(value + ", ");
Java HashSet
In Java, HashSet is commonly used if we have to access elements randomly. It is because
elements in a hash table are accessed using hash codes. The hashcode of an element is a
unique identity that helps to identify the element in a hash table. HashSet cannot contain
duplicate elements. Hence, each hash set element has a unique hashcode.
A HashSet is a collection of items where every item is unique, and it is found in
the java.util package:
import java.util.HashSet; // Import the HashSet class
HashSet<String> cars = new HashSet<String>();
Add Items
cars.add("Ford");
cars.add("BMW");
cars.add("Mazda");
System.out.println(cars);
Check If an Item Exists
cars.contains("Mazda");
Remove an Item
cars.remove("Volvo");
To remove all items, cars.clear();
HashSet Size
cars.size();
Loop Through a HashSet
for (String i : cars) {
System.out.println(i);
}
Example Program:
import java.util.*;
class HashSetSample
{
public static void main(String[] args)
{
Set<String> h = new HashSet<String>();
h.add("India");
h.add("Australia");
h.add("South Africa");
// Adding the duplicate element
h.add("India");
// Displaying the HashSet
System.out.println(h);
h.remove("Australia");
System.out.println("Set after removing " + "Australia:" + h);
System.out.println("Iterating over set:");
Iterator<String> i = h.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
LinkedHashSet
*maintains a doubly-linked List
*when the iteration order is needed
* When iterating through a HashSet the order is unpredictable, while a
LinkedHashSet lets us iterate through the elements in the order in which they were
inserted.
import java.util.*;
class LinkedHashsetExample {
public static void main(String[] args)
{
Set<String> lh = new LinkedHashSet<String>();
// Adding elements into the LinkedHashSet using add()
lh.add("India");
lh.add("Australia");
lh.add("South Africa");
// Adding the duplicate element
lh.add("India");
// Displaying the LinkedHashSet
System.out.println(lh);
// Removing items from LinkedHashSet
// using remove()
lh.remove("Australia");
System.out.println("Set after removing "+ "Australia:" + lh);
// Iterating over linked hash set items
System.out.println("Iterating over set:");
Iterator<String> i = lh.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
TreeSet
it stores elements in a sorted format.
TreeSet uses a tree data structure for storage.
Objects are stored in sorted, ascending order.
TreeSet.descendingIterator() - iterate in descending order
import java.util.*;
class TreeSetExample
{
public static void main(String[] args)
{
Set<String> ts = new TreeSet<String>();
ts.add("India");
ts.add("Australia");
ts.add("South Africa");
// Adding the duplicate element
ts.add("India");
// Displaying the TreeSet
System.out.println(ts);
// Removing items from TreeSet
ts.remove("Australia");
System.out.println("Set after removing "+ "Australia:" +
ts);
// Iterating over Tree set items
System.out.println("Iterating over set:");
Iterator<String> i = ts.iterator();
while (i.hasNext())
System.out.println(i.next());
}
}
Difference between List, Set, and Map in Java
List Set Map
The list interface allows Set does not allow The map does not allow duplicate
duplicate elements duplicate elements. elements
The list maintains Set do not maintain any The map also does not maintain any
insertion order. insertion order. insertion order.
We can add any number of But in set almost only The map allows a single null key at
null values. one null value. most and any number of null values.
List implementation Set implementation Map implementation classes
classes are Array classes are HashMap, HashTable, TreeMap, C
List Set Map
are HashSet, LinkedHash oncurrentHashMap,
List, LinkedList. Set, and TreeSet. and LinkedHashMap.
Set does not provide get The map does not provide get
The list provides get() method to get the method to get the elements at a
method to get the element elements at a specified specified index
at a specified index. index
If you need to access the If you want to create a
elements frequently by collection of unique If you want to store the data in the
using the index then we elements then we can form of key/value pair then we can
can use the list use set use the map.
To traverse the list
elements by using Iterator can be used
Listlterator. traverse the set elements Through keyset, value, and entry set.