Sets in Java - notes
Sets in Java - notes
Methods:
add(element)
addAll(collection)
clear()
contains(element)
containsAll(collection)
isEmpty()
iterator()
remove(element)
removeAll(collection)
size()
Example:
Output
[Set, Example, Geeks, For]
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>();
// 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);
hs.remove("B");
Example Program:
import java.util.*;
class HashSetSample
{
h.add("India");
h.add("Australia");
h.add("South Africa");
h.remove("Australia");
System.out.println("Set after removing " + "Australia:" + h);
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 {
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");
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.
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