Table of contents
1.
Introduction
2.
What is Set Collection in Java?
3.
What is a framework in Java?
4.
Hierarchy of Collection Framework
5.
Methods of Collection interface
6.
Iterator interface
7.
Iterable Interface
8.
Collection Interface
9.
List Interface
10.
ArrayList
11.
LinkedList
12.
Vector
13.
Stack
14.
Queue Interface
15.
PriorityQueue
16.
Deque Interface
17.
ArrayDeque
18.
Set Interface
19.
HashSet
20.
LinkedHashSet
21.
SortedSet Interface
22.
TreeSet
23.
Classes Implementing Set Interface
24.
Interface Extending Set
25.
Various Methods in Set Interface
26.
Implementing Various Set Operations in Java
27.
Performing Various Operations on SortedSet
28.
Frequently Asked Questions
28.1.
What is Collection in Java?
28.2.
What is CopyOnWriteArraySet in Set Interface?
28.3.
Which Java collection framework class should you use if you don't need duplicates?
28.4.
What is the main difference between a list and a set?
29.
Conclusion 
Last Updated: Mar 27, 2024
Easy

Collections in Java

Author Akash
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Collections in Java is a group of objects represented as a single unit. They are an integral part of any programming language, and Java is no exception. The Java Collection Framework provides a well-designed set of interfaces and classes that allows developers to work with collections of objects consistently and efficiently.

set collection in java

This blog will discuss set collections in Java and how to use them in detail. Let's start going!

What is Set Collection in Java?

Set collection in Java is used to store a group of unique elements. It is an interface that extends the Collection interface. The Set interface specifies methods for adding, removing and checking for the presence of elements, and it does not allow duplicate elements.

A set collection in Java is commonly used to store a collection of unique elements, such as a list of unique words in a text, a list of unique IP addresses, etc.

The Set Interface is part of the java.util.package in java. It provides several helpful methods like add()remove(), and contains(), etc.; these methods make it quite useful when working with a certain type of data.

Also read, Duck Number in Java and Hashcode Method in Java.

What is a framework in Java?

A framework in Java refers to a pre-defined set of classes and interfaces that provide a structured and reusable solution for developing applications. It provides a foundation for developers to build upon, offering ready-made functionalities and structures that help simplify the development process and promote code reuse. Frameworks in Java often follow specific design patterns and conventions, offering standardized ways to solve common programming problems.

Hierarchy of Collection Framework

The Java Collection Hierarchy defines the relationships between interfaces and classes in the Collections framework. It provides efficient storage, manipulation, and processing of data structures in Java.

The hierarchy consists of four core interfaces: Collection, List, Set, and Map. Additionally, there are specialized interfaces for sorting: SortedSet and SortedMap.

All the interfaces and classes related to the collection framework reside in the java.util package. The diagram below illustrates the Java collection hierarchy.

Hierarchy of Collection Framework

Inheritance is established using the "extends" keyword for classes and interfaces, while the "implements" keyword is used for inheritance between a class and an interface.

Methods of Collection interface

Method Description
boolean add(E element) The element you provide is added to the collection. If the collection has been updated, it returns true.
boolean remove(Object o) the first instance of the provided element is removed from the collection. If the element was located and eliminated, it returns true.
boolean contains(Object o) determines whether the requested element is present in the collection. It returns true if the element is found.
int size() returns the collection's total number of elements.
boolean isEmpty() evaluates whether the collection is empty. returns true if there are no elements in the collection.
void clear() Deletes each and every element from the collection.
boolean containsAll(Collection<?> c) determines whether every element of the supplied collection is present in the collection. If all of the components are located, it returns true.
boolean addAll(Collection<? extends E> c) adds all of the specified collection's items to the collection. True is returned if the collection has been altered.
boolean removeAll(Collection<?> c) All objects that are also part of the specified collection are removed from the collection. If the collection has been updated, it returns true.
boolean retainAll(Collection<?> c) Removes every element from the collection that is not also present in the given collection. True is returned if the collection has been altered.
Object[] toArray() returns a list of all the collection's elements in an array.
Iterator<E> iterator() returns an iterator that iterates across the collection's elements.

Iterator interface

Iterator interface in Java provides methods to iterate over elements in a collection. It allows sequential access to elements and supports operations like hasNext() to check if there are more elements, and next() to retrieve the next element.

Here's a table listing some methods of the Iterator interface along with their descriptions:

Method

Description

boolean hasNext() Returns true if there are more elements to iterate over.
E next() Returns the next element in the iteration.
void remove() Removes the last element returned by the iterator from the underlying collection.
default void forEachRemaining(Consumer<? super E> action) Performs the given action for each remaining element until all elements have been processed or the action throws an exception.

The Iterator interface provides a way to traverse and manipulate elements in a collection sequentially. It is commonly used in conjunction with the enhanced for-loop syntax to iterate over elements in a collection.

Iterable Interface

A group of elements that can be consecutively iterated is represented by the Iterable interface in Java. It offers the iterator() method, which returns an Iterator object and enables the for-each loop traversal of the elements. 

For example:

List<String> names = new ArrayList<>();
names.add("Josh");
names.add("Musk");
names.add("Alok");

for (String name : names) {
    System.out.println(name);
}

Collection Interface

The Java Collections Framework's root interface is the Collection interface. It symbolises a collection of things referred to as elements. It offers all-purpose tools for modifying and searching collections. 

For example:

List<String> names = new ArrayList<>();
names.add("Josh");
names.add("Musk");
names.add("Alok");


System.out.println(names.size()); // Output: 3
System.out.println(names.contains("Musk")); // Output: true
names.remove("Josh");
System.out.println(names); // Output: [Musk, Alok]

List Interface

An ordered collection of elements is represented by the List interface, which extends the Collection interface. Both duplicate elements and the insertion order are preserved. 

For example:

List<String> names = new ArrayList<>();
names.add("Josh");
names.add("Musk");
names.add("Alok");


System.out.println(names.get(0)); // Output: Josh
System.out.println(names.size()); // Output: 3
names.remove("Musk");
System.out.println(names); // Output: [Josh, Alok]

ArrayList

An implementation of the List interface called ArrayList stores its elements in a resizable array. It offers quick random access and effective insertion and deletion at the conclusion. 

For example:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);


System.out.println(numbers.get(1)); // Output: 20
System.out.println(numbers.size()); // Output: 3
numbers.remove(0);
System.out.println(numbers); // Output: [20, 30]

LinkedList

Another implementation of the List interface, LinkedList, stores entries in a doubly-linked list. At both ends, it offers effective insertion and deletion, but random access is slower. 

For example:

LinkedList<String> cities = new LinkedList<>();
cities.add("New Delhi");
cities.add("Lucknow");
cities.add("Trichi");


System.out.println(cities.get(1)); // Output: Lucknow
System.out.println(cities.size()); // Output: 3
cities.removeLast();
System.out.println(cities); // Output: [New Delhi, Lucknow]

Vector

Vector is a synchronized, thread-safe legacy implementation of the List interface. It offers ArrayList-like capabilities but with added thread safety.  

For example:

Vector<Integer> numbers = new Vector<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);


System.out.println(numbers.get(2)); // Output: 30
System.out.println(numbers.size()); // Output: 3
numbers.removeElementAt(1);
System.out.println(numbers); // Output: [10, 30]

Stack

A last-in, first-out (LIFO) stack of items is represented by the subclass of Vector called Stack. It offers particular stack operations, such as pop() and push(). 

For example:

Stack<String> stack = new Stack<>();
stack.push("Apple");
stack.push("Banana");
stack.push("Orange");


System.out.println(stack.pop()); // Output: Orange
System.out.println(stack.size()); // Output: 2
System.out.println(stack.peek()); // Output: Banana

Queue Interface

In Java, a collection that retains elements in a particular sequence for processing is represented by the queue interface. The First-In-First-Out (FIFO) principle is used, in which items are inserted at the end and subtracted from the beginning. 

For example:

Queue<String> queue = new LinkedList<>();
queue.add("Apple");
queue.add("Banana");
queue.add("Orange");


System.out.println(queue.poll()); // Output: Apple
System.out.println(queue.size()); // Output: 2
System.out.println(queue.peek()); // Output: Banana

PriorityQueue

PriorityQueue uses a custom comparator or the components' natural ordering to determine how they are arranged. Higher priority elements are the first to be dequeued. 

For example:

PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(10);
queue.add(30);
queue.add(20);


System.out.println(queue.poll()); // Output: 10
System.out.println(queue.size()); // Output: 2
System.out.println(queue.peek()); // Output: 20

Deque Interface

An element can be added to or removed from a linear collection at both ends thanks to the Java Deque interface (Double Ended Queue). AddFirst(), AddLast(), RemoveFirst(), and RemoveLast() are among the operations that are supported. 

For example:

Deque<String> deque = new ArrayDeque<>();
deque.addFirst("Apple");
deque.addLast("Banana");
deque.addLast("Orange");


System.out.println(deque.removeLast()); // Output: Orange
System.out.println(deque.size()); // Output: 2
System.out.println(deque.getFirst()); // Output: Apple

ArrayDeque

The Deque interface is implemented by ArrayDeque, which stores elements in a resizable array. It is not thread-safe but offers effective insertion and removal at both ends.  

For example:

ArrayDeque<Integer> deque = new ArrayDeque<>();
deque.addFirst(10);
deque.addLast(20);
deque.addLast(30);


System.out.println(deque.removeFirst()); // Output: 10
System.out.println(deque.size()); // Output: 2
System.out.println(deque.getLast()); // Output: 30

Set Interface

Java's Set interface represents a collection with distinct elements. It does not preserve any particular sequence and does not permit duplicate elements. 

For example:

Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");
set.add("Banana"); // Duplicate, not added


System.out.println(set.size()); // Output: 3
System.out.println(set.contains("Apple")); // Output: true
set.remove("Orange");
System.out.println(set); // Output: [Apple, Banana]

HashSet

An implementation of the Set interface called HashSet stores components in a hash table. It does not guarantee the order of the elements but does provide constant-time performance for basic operations. 

For example:

HashSet<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(30);
set.add(20); // Duplicate, not added


System.out.println(set.size()); // Output: 3
System.out.println(set.contains(10)); // Output: true
set.remove(30);
System.out.println(set); // Output: [10, 20]

LinkedHashSet

The LinkedHashSet implementation of the Set interface preserves the order in which elements are inserted. It offers effective iteration and predictable order by combining a linked list and hash table.

For example:

LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");


System.out.println(set.size()); // Output: 3
System.out.println(set.contains("Apple")); // Output: true
set.remove("Banana");
System.out.println(set); // Output: [Apple, Orange]

SortedSet Interface

Java's SortedSet interface provides a sorted collection of elements and extends the Set interface. According to a customized comparator or by default, it keeps the elements in ascending order.  

For example:

SortedSet<Integer> set = new TreeSet<>();
set.add(30);
set.add(10);
set.add(20);


System.out.println(set.first()); // Output: 10
System.out.println(set.size()); // Output: 3
System.out.println(set.last()); // Output: 30

TreeSet

The SortedSet interface is implemented by TreeSet, which stores elements in a tree structure. For retrieving elements in sorted order, it offers effective operations.  

For example:

TreeSet<String> set = new TreeSet<>();
set.add("Apple");
set.add("Banana");
set.add("Orange");

System.out.println(set.first()); // Output: Apple
System.out.println(set.size()); // Output: 3
System.out.println(set.last()); // Output: Orange

Classes Implementing Set Interface

set interface

A class can offer a collection of distinct elements, with duplicates disallowed, by implementing the Set interface. It gives the class a means of complying with a predefined set of procedures for modifying the collection's elements, such as adding and removing items, determining whether or not items are present, and iterating over them.

The classes that implement the Set interface in Java are:-

1. HashSet: This class uses a hash table for storage, which provides fast lookups, and insertion times. It does not guarantee any specific order of the elements.

2. TreeSet: This class uses a Red-Black tree for storage, which provides efficient ordering of the elements. The elements in a TreeSet are ordered according to their natural order or by a specified Comparator.

3. LinkedHashSet: This class uses a hash table with a linked list running through it. The order of the elements is the order in which they were inserted into the set.

4. EnumSet: This class is a specialized Set for use with enumerated types.

Interface Extending Set

interface extending set

An interface in java is a blueprint for a class. It does not provide an implementation for the methods it defines, which a class must implement. It is used to achieve abstraction in java.

A few interfaces in the Java standard library extend the Java.util.Set interface are:-

1. SortedSet:- The SortedSet interface extends the Set interface to provide an ordered set. This means that the elements in a SortedSet are ordered in a specific way, typically based on their natural ordering or according to a specified Comparator. 

The SortedSet interface provides methods for retrieving the first and last elements in the set and subsets based on a range of elements.

Here is an example of how to use Java.util.TreeSet class, which is a SortedSet implementation:

// Creating SoortedSet
SortedSet < Integer > sorS = new TreeSet < Integer > ();
sorS.add(5);
sorS.add(4);
sorS.add(2);
// prints [2, 4, 5]
System.out.println(sorS);

 

2. NavigableSet:- It is another interface in Java that extends SortedSet, and provides navigation methods like a lower(), floor(), ceiling(), and higher(). It also provides additional methods like pollFirst() and pollLast().

You can use the NavigableSet interface or TreeSet class to sort and navigate.

// Creating NavigableSet
NavigableSet < Integer > navSet = new TreeSet < Integer > ();
navSet.add(5);
navSet.add(4);
navSet.add(2);
// prints 2
System.out.println(navSet.ceiling(2));

 

You can also read about the topic of Java Destructor  and Swap Function in Java.

Various Methods in Set Interface

The Set interface in Java defines several methods for working with sets, which include:

1. add(e): It adds an element to the set. Here, e is the element to be inserted.

Syntax: 

boolean add(e);


2. addAll(Collection c): It adds all the elements in a collection to the set.

Syntax: 

boolean addAll(Collection<? extends E> c);

 

3. clear():  It removes all elements from the set.

Syntax:

void clear();


4. contains(Object o): It always returns true if the set contains the specific element.

Syntax:

boolean contains(Object o);

 

5. containsAll(Collection c): It returns true if the set contains all the elements in the specified collection.

Syntax:

boolean containsAll(Collection<?> c);

 

6. isEmpty(): It returns true if the set is null.

Syntax:

boolean isEmpty();

7. iterator(): It returns an iterator over the elements in the set.

Syntax: 

Iterator<E> iterator();

 

8. remove(Object o): It removes an element from the set.

Syntax:

boolean remove(Object o);

 

9. removeAll(Collection c): It removes all the elements in a collection from the set.

Syntax:

boolean removeAll(Collection<?> c);


10. retainAll(Collection c): It removes all elements from the set that are not contained in the specified collection.

Syntax:

boolean retainAll(Collection<?> c);


11. size(): It returns the number of elements in the set.

Syntax:

int size();

Implementing Various Set Operations in Java

Set Collection in Java defines standard operations methods, such as union, intersection, and difference. 

1. Union: The elements that are present in either of the two sets are returned by this operation. 

For Example:-

Let us suppose 2 sets, A : [1,2,3,4], and B : [2,3,4,5].

So, the Union of A and B is [1,2,3,4,5].

Implementation of Union using HashSet is:

import java.util.*;
class Main { 
    public static void main(String[] args) {     
        Set < Integer > set1 = new HashSet < Integer > (Arrays.asList(1, 2, 3));    
        Set < Integer > set2 = new HashSet < Integer > (Arrays.asList(2, 3, 4));
        set1.addAll(set2);
        System.out.println(set1);
    }
}


Output:

[1, 2, 3, 4]


2. Intersection: The elements that are present in both sets are returned by this operation. 

For Example:-

Let us suppose 2 sets, A : [1,2,3,4], and B : [2,3,4,5].

So, the Intersection of A and B is [2,3].

Implementation of  Intersection using HashSet is:

import java.util.*;
class Main { 
    public static void main(String[] args) {  
        Set < Integer > set1 = new HashSet < Integer > (Arrays.asList(1, 2, 3));  
        Set < Integer > set2 = new HashSet < Integer > (Arrays.asList(2, 3, 4));
        Set < Integer > intersection = new HashSet < Integer > (set1);
        intersection.retainAll(set2);
        System.out.println(intersection);
    }
}

 

Output:

[2, 3]


3. Difference: This operation removes all the values in one set that are present in the other set. 

For Example:-

Let us suppose 2 sets, A : [1,2,3], and B : [2,3,4].

So, the Difference between A and B is [1].

Implementation of Difference using HashSet is:

import java.util.*;
class Main { 
    public static void main(String[] args) {  
        Set < Integer > set1 = new HashSet < Integer > (Arrays.asList(1, 2, 3));
        Set < Integer > set2 = new HashSet < Integer > (Arrays.asList(2, 3, 4));
        Set < Integer > difference = new HashSet < Integer > (set1);
        difference.removeAll(set2);
        System.out.println(difference);
    }
}

 

Output:

[1]

Performing Various Operations on SortedSet

A SortedSet in Java is a collection that maintains its elements in sorted order. It provides operations to add, remove, and retrieve elements based on their ordering. Here's a concise example:

import java.util.SortedSet;
import java.util.TreeSet;

SortedSet<Integer> sortedSet = new TreeSet<>();

sortedSet.add(5);
sortedSet.add(2);
sortedSet.add(8);

int firstElement = sortedSet.first();
int lastElement = sortedSet.last();

boolean containsElement = sortedSet.contains(4);

sortedSet.remove(2);

SortedSet<Integer> subset = sortedSet.subSet(1, 5);

sortedSet.clear();

 

In this example, we create a SortedSet using the TreeSet implementation. We can add elements, retrieve the first and last elements, check if an element exists, remove an element, get a subset of elements within a range, and clear all elements from the sorted set.

Must Read Type Conversion in Java

Frequently Asked Questions

What is Collection in Java?

The Collection framework in Java is a set of interfaces and classes that provide a standardized way of working with groups of objects. It is a part of the Java Standard Library and is used for creating, storing, and manipulating collections of objects.

What is CopyOnWriteArraySet in Set Interface?

It is a class that is a modified version of the HashSet Interface that is thread-safe. It employs a copy-on-write technique that performs better when the set is essentially immutable. Each mutation operation creates a unique copy of the underlying array.

Which Java collection framework class should you use if you don't need duplicates?

Use a Set Collection in Java if you don't need duplicates. The Set interface defines a group of distinct elements and extends the Collection interface. HashSet, TreeSet, and LinkedHashSet are just a few classes that implement the Set interface.

What is the main difference between a list and a set?

Set is an unsorted collection that does not permit duplicate elements and only permits one null element. The list, which is an ordered collection, does not permit duplicates. The list can contain null elements as well.

Conclusion 

Congratulations on finishing the blog! We have discussed the Collections in Java. The Set is a collection of unique elements. It does not allow duplicate elements, and elements are unordered.

We hope this blog has helped you enhance your knowledge of set collection in Java. Do not stop learning! We recommend you read some of our Java articles: 

1. Introduction to Java

2. Separator in Java

3. Java Swing

4. Super Keyword In Java

You can also consider our paid courses such as DSA in Java to give your career an edge over others!

We wish you Good Luck!

Live masterclass