0% found this document useful (0 votes)
32 views7 pages

Understanding Sets in Java

this consists of the topic of sets in java

Uploaded by

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

Understanding Sets in Java

this consists of the topic of sets in java

Uploaded by

Chinnu Jashuva
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Set in Java

 The set interface is present in [Link] 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


[Link](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>();

[Link]([Link](new Integer[] { 1, 3, 2, 4, 8, 9, 0 }));


Set<Integer> b = new HashSet<Integer>();
[Link]([Link](new Integer[] { 1, 3, 7, 5, 4, 0, 7, 5 }));

// To find union
Set<Integer> union = new HashSet<Integer>(a);
[Link](b);
[Link]("Union of the two Set");
[Link](union);

// To find intersection
Set<Integer> intersection = new HashSet<Integer>(a);
[Link](b);
[Link]("Intersection of the two Set");
[Link](intersection);

// To find the symmetric difference


Set<Integer> difference = new HashSet<Integer>(a);
[Link](b);
[Link]("Difference of the two Set");
[Link](difference);

Performing Various Operations on SortedSet


 Adding Elements

Set<String> hs = new HashSet<String>();


// Adding elements to above object
// using add() method
[Link]("B");
[Link]("B");
[Link]("C");
[Link]("A");

// Printing the elements inside the Set object


[Link](hs);

 Accessing the Elements

String check = "D";

// Check if the above string exists in


// the SortedSet or not
// using contains() method
[Link]("Contains " + check + " "+ [Link](check));

 Removing the Values

[Link]("B");

// Printing Set elements after removing an element


// and printing updated Set elements
[Link]("After removing element " + hs);
 Iterating through the Set

for (String value : hs)

// Printing all the values inside the object


[Link](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 [Link] package:

import [Link]; // Import the HashSet class


HashSet<String> cars = new HashSet<String>();
 Add Items
[Link]("Ford");
[Link]("BMW");
[Link]("Mazda");
[Link](cars);
 Check If an Item Exists
[Link]("Mazda");
 Remove an Item
[Link]("Volvo");
 To remove all items, [Link]();
 HashSet Size
[Link]();
 Loop Through a HashSet
for (String i : cars) {
[Link](i);
}

Example Program:

import [Link].*;

class HashSetSample
{

public static void main(String[] args)


{
Set<String> h = new HashSet<String>();

[Link]("India");
[Link]("Australia");
[Link]("South Africa");

// Adding the duplicate element


[Link]("India");

// Displaying the HashSet


[Link](h);

[Link]("Australia");
[Link]("Set after removing " + "Australia:" + h);

[Link]("Iterating over set:");

Iterator<String> i = [Link]();

while ([Link]())
[Link]([Link]());
}
}

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 [Link].*;
class LinkedHashsetExample {

public static void main(String[] args)


{
Set<String> lh = new LinkedHashSet<String>();

// Adding elements into the LinkedHashSet using add()


[Link]("India");
[Link]("Australia");
[Link]("South Africa");

// Adding the duplicate element


[Link]("India");

// Displaying the LinkedHashSet


[Link](lh);

// Removing items from LinkedHashSet


// using remove()
[Link]("Australia");
[Link]("Set after removing "+ "Australia:" + lh);

// Iterating over linked hash set items


[Link]("Iterating over set:");
Iterator<String> i = [Link]();
while ([Link]())
[Link]([Link]());
}
}

TreeSet
 it stores elements in a sorted format.
 TreeSet uses a tree data structure for storage.
 Objects are stored in sorted, ascending order.
 [Link]() - iterate in descending order
import [Link].*;
class TreeSetExample
{
public static void main(String[] args)
{
Set<String> ts = new TreeSet<String>();

[Link]("India");
[Link]("Australia");
[Link]("South Africa");

// Adding the duplicate element


[Link]("India");

// Displaying the TreeSet


[Link](ts);

// Removing items from TreeSet


[Link]("Australia");
[Link]("Set after removing "+ "Australia:" +
ts);

// Iterating over Tree set items


[Link]("Iterating over set:");
Iterator<String> i = [Link]();
while ([Link]())
[Link]([Link]());
}
}

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.

Common questions

Powered by AI

The choice of Set implementation among HashSet, LinkedHashSet, and TreeSet is influenced by their memory management and order characteristics. HashSet provides efficient memory usage with average constant-time complexity for add, remove, and contains operations, but does not guarantee any order of elements . LinkedHashSet offers predictable iteration order by maintaining elements in insertion order, which incurs additional memory overhead due to the linked list structure, but still provides similar time complexity to HashSet for most operations . TreeSet guarantees elements are stored in natural order or by a specified comparator, which is ideal for sorted data requiring consistent iteration order, but this comes at the cost of slower operations due to log(n) time complexity . Therefore, the choice depends on whether order preservation or sorting is needed (favoring LinkedHashSet or TreeSet) or if performance is paramount (favoring HashSet).

To determine if a specific element exists within a Set, you would use the "contains(element)" method, which returns a boolean value indicating whether the set contains the specified element . In the case of HashSet, the "contains" operation generally has constant time complexity, O(1), due to the underlying hash table structure, making it highly efficient for element existence checks . In TreeSet, this operation is O(log n) as it involves searching in a sorted set via a tree structure .

When you try to add duplicate elements into a HashSet, the duplicate elements are not stored. This prevention of duplicates is made possible through the use of hash code values. Each element in a HashSet is assigned a hash code, which serves as a unique identifier to detect duplicates. If an element with the same hash code already exists in the HashSet, the add operation will not store the new element as it is seen as a duplicate of an existing one . This ensures the uniqueness of elements within a HashSet .

The TreeSet class handles element ordering by storing elements in a sorted manner according to their natural ordering or by a custom comparator provided at the TreeSet instantiation. This ordering is maintained using a self-balancing binary search tree (such as a Red-Black tree). The benefit of this mechanism is that it provides efficient and easy access to ordered elements, which is useful for applications like in-order traversal, range views, or sub-set retrieval operations. Additionally, TreeSet supports navigation operations like floor, ceiling, and subset, which are not possible with unordered collections .

HashSet and TreeSet are both implementations of the Set interface in Java but differ in their underlying data structure and element ordering. HashSet uses a hash table for storage, resulting in an unpredictable iteration order, which makes it capable of fast access, search, and insertion operations . In contrast, TreeSet uses a tree data structure, storing elements in a sorted, ascending order, and thus provides an orderly iteration through elements while offering additional functionality such as navigation methods . TreeSet also has slightly slower time complexity for basic operations than HashSet due to the overhead of maintaining order .

To find the intersection of two sets in Java, you can use the "retainAll(collection)" method. This method modifies the invoking set to contain only the elements that are also contained in the specified collection, effectively performing an intersection operation . For example, if we have Set a with elements {1, 3, 2, 4, 8, 9, 0} and Set b with elements {1, 3, 7, 5, 4, 0, 7, 5}, the intersection set would be {0, 1, 3, 4}, as these are the elements common to both sets .

The Set interface in Java enforces uniqueness by not allowing duplicate elements, which is achieved through implementations like HashSet, LinkedHashSet, and TreeSet that manage elements differently but ensure each stored element is unique. This uniqueness constraint helps in scenarios where the data integrity of the collection is important, like maintaining a collection of IDs, ensuring no duplicate IDs exist . It also simplifies operations that naturally rely on uniqueness, such as finding the union, intersection, or difference of sets, which are easily manageable without worrying about duplicates .

The Java Set interface has limitations regarding element access because it does not provide indexed access to its elements. Unlike a List, which allows getting elements based on their position using methods like "get(index)", a Set is designed to solely ensure uniqueness and does not maintain any order or indexed positions for its elements. This lack of indexing means operations that involve positional access or iteration in a predefined order can't be efficiently handled by a Set . In contrast, the List interface supports both ordering guaranteed by insertion and position-based access, making it more suitable when ordered iteration or random access is required .

A developer might choose to use a LinkedHashSet instead of a HashSet when they require the elements to be iterated in the order they were inserted. Unlike HashSet, LinkedHashSet maintains a doubly-linked list structure that preserves insertion order . This feature is beneficial in applications where predictable iteration order is important, such as maintaining a chronological list of transactions or user actions where the order of operations is significant for auditing or processing purposes. Additionally, LinkedHashSet provides all the functionality of a HashSet, such as fast lookup and unique element constraints, but with additional overhead to maintain the order .

Using a Set over a Map in Java presents distinct trade-offs, driven by their structural differences. A Set is designed to hold unique elements without an associated key, which makes it ideal for scenarios where uniqueness is paramount without the need for key-value associations, such as a collection of unique items . Its operations focus on element management, like membership tests and collection algebra (union, intersection, difference). Conversely, a Map stores key-value pairs and provides efficient means to associate, retrieve, and manipulate combinations of objects, which is integral in situations requiring fast access to particular values associated with known keys, such as configuration settings retrieval . The trade-off rests on whether the task at hand benefits more from the simplicity and uniqueness constraint of a Set, or the associative capabilities and key-based access of a Map.

You might also like