0% found this document useful (0 votes)
54 views108 pages

Java Unit 4 Part A Notes

Uploaded by

Arib Ahmed
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)
54 views108 pages

Java Unit 4 Part A Notes

Uploaded by

Arib Ahmed
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/ 108

UNIT 4

Collections in Java
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java

o It provides readymade architecture.


o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.

List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have
duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.

The classes that implement the List interface are given below.

Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array,
but there is no size limit. We can add or remove elements anytime. So, it is much
more flexible than the traditional array. It is found in the java.util package. It is like
the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List
interface so we can use all the methods of the List interface here. The ArrayList
maintains the insertion order internally.

It inherits the AbstractList class and implements List interface.

The important points about the Java ArrayList class are:

o Java ArrayList class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because the array works on an index basis.
o In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot
of shifting needs to occur if any element is removed from the array list.
o We can not create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:

1. ArrayList<int> al = ArrayList<int>(); // does not work


2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
o Java ArrayList gets initialized by the size. The size is dynamic in the array list, which
varies according to the elements getting added or removed from the list.
o ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced
to have the only specified type of object in it. If you try to add another type of object,
it gives a compile-time error.

Java ArrayList Example


FileName: ArrayListExample1.java

import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Printing the arraylist object
System.out.println(list);
}
}

Output:

[Mango, Apple, Banana, Grapes]

Iterating ArrayList using Iterator


Let's see an example to traverse ArrayList elements using the Iterator interface.

FileName: ArrayListExample2.java

import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to next
}
}
}

Output:

Mango
Apple
Banana
Grapes

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

FileName: ArrayListExample3.java

import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
for (String i : cars) {
System.out.println(i);
}
}
}

Output:
Get and Set ArrayList
The get() method returns the element at the specified index, whereas the set()
method changes the element.

FileName: ArrayListExample4.java

import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will return the 2nd element, because ind
ex starts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);

Output:

Returning element: Apple


Mango
Dates
Banana
Grapes

How to Sort ArrayList


The java.util package provides a utility class Collections, which has the static method
sort(). Using the Collections.sort() method, we can easily sort the ArrayList.

FileName: SortArrayList.java
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1);
//Traversing list through the for-each loop
for(String fruit:list1)
System.out.println(fruit);

}
} Output:
Apple
Banana
Grapes
Mango

Java ArrayList example to remove elements


Here, we see different ways to remove an element.

1. Removing specific element from arraylist


al.remove("Vijay");
2. Removing element on the basis of specific position
al.remove(0);
3. Adding new elements to arraylist
al.addAll(al2);
4. Removing all the new elements from arraylist
al.removeAll(al2);
5. Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay"));
6. Removing all the elements available in the list
al.clear();
FileName: ArrayList8.java

import java.util.*;
class ArrayList8 {

public static void main(String [] args)


{
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
al.add("Anuj");
al.add("Gaurav");
System.out.println("An initial list of elements: "+al);
//Removing specific element from arraylist
al.remove("Vijay");
System.out.println("After invoking remove(object) method: "+al);
//Removing element on the basis of specific position
al.remove(0);
System.out.println("After invoking remove(index) method: "+al);

//Creating another arraylist


ArrayList<String> al2=new ArrayList<String>();
al2.add("Ravi");
al2.add("Hanumat");
//Adding new elements to arraylist
al.addAll(al2);
System.out.println("Updated list : "+al);
//Removing all the new elements from arraylist
al.removeAll(al2);
System.out.println("After invoking removeAll() method: "+al);
//Removing elements on the basis of specified condition
al.removeIf(str -> str.contains("Ajay")); //Here, we are using Lambda expression
System.out.println("After invoking removeIf() method: "+al);
//Removing all the elements available in the list
al.clear();
System.out.println("After invoking clear() method: "+al);
}
}

Output:

An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]


After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []

Java ArrayList example of isEmpty() method

To check whether list is empty or not


FileName: ArrayList4.java

1. import java.util.*;
2. class ArrayList10{
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. System.out.println("Is ArrayList Empty: "+al.isEmpty());
8. al.add("Ravi");
9. al.add("Vijay");
10. al.add("Ajay");
11. System.out.println("After Insertion");
12. System.out.println("Is ArrayList Empty: "+al.isEmpty());
13. }
14. }

Output:

Is ArrayList Empty: true


After Insertion

Is ArrayList Empty: false


Size and Capacity of an ArrayList
Size and capacity of an array list are the two terms that beginners find confusing.
Let's understand it in this section with the help of some
examplesFileName: SizeCapacity.java

1. import java.util.*;
2.
3. public class SizeCapacity
4. {
5.
6. public static void main(String[] args) throws Exception
7. {
8.
9. ArrayList<Integer> al = new ArrayList<Integer>();
10.
11. System.out.println("The size of the array is: " + al.size());
12. }
13. }

Output:

The size of the array is: 0

Explanation: The output makes sense as we have not done anything with the array
list. Now observe the following program.

FileName: SizeCapacity1.java

1. import java.util.*;
2.
3. public class SizeCapacity1
4. {
5.
6. public static void main(String[] args) throws Exception
7. {
8.
9. ArrayList<Integer> al = new ArrayList<Integer>(10);
10.
11. System.out.println("The size of the array is: " + al.size());
12. }
13. }

Output:

The size of the array is: 0

Explanation: We see that the size is still 0, and the reason behind this is the number
10 represents the capacity no the size. In fact, the size represents the total number of
elements present in the array. As we have not added any element, therefore, the size
of the array list is zero in both programs.

Capacity represents the total number of elements the array list can contain.
Therefore, the capacity of an array list is always greater than or equal to the size of
the array list. When we add an element to the array list, it checks whether the size of
the array list has become equal to the capacity or not. If yes, then the capacity of the
array list increases. So, in the above example, the capacity will be 10 till 10 elements
are added to the list. When we add the 11th element, the capacity increases. Note
that in both examples, the capacity of the array list is 10. In the first case, the capacity
is 10 because the default capacity of the array list is 10. In the second case, we have
explicitly mentioned that the capacity of the array list is 10.

Note: There is no any standard method to tell how the capacity increases in the array
list. In fact, the way the capacity increases vary from one GDK version to the other
version. Therefore, it is required to check the way capacity increases code is
implemented in the GDK. There is no any pre-defined method in the ArrayList class that
returns the capacity of the array list. Therefore, for better understanding, use the
capacity() method of the Vector class. The logic of the size and the capacity is the same
in the ArrayList class and the Vector class.
Java Vector
The Vector class is an implementation of the List interface that allows us to
create resizable-arrays similar to the ArrayList class.

Java Vector vs. ArrayList


In Java, both ArrayList and Vector implements the List interface and
provides the same functionalities. However, there exist some differences
between them.
The Vector class synchronizes each individual operation. This means
whenever we want to perform some operation on vectors, the Vector class
automatically applies a lock to that operation.

Note: It is recommended to use ArrayList in place of Vector because


vectors are less efficient.

Creating a Vector
Here is how we can create vectors in Java.

Vector<Type> vector = new Vector<>();

Here, Type indicates the type of a linked list. For example,

// create Integer type linked list


Vector<Integer> vector= new Vector<>();
// create String type linked list
Vector<String> vector= new Vector<>();

Methods of Vector
The Vector class also provides the resizable-array implementations of
the List interface (similar to the ArrayList class). Some of
the Vector methods are:

Add Elements to Vector


 add(element) - adds an element to vectors
 add(index, element) - adds an element to the specified position
 addAll(vector) - adds all elements of a vector to another vector
For example,

import java.util.Vector;

class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<>();

// Using the add() method


mammals.add("Dog");
mammals.add("Horse");

// Using index number


mammals.add(2, "Cat");
System.out.println("Vector: " + mammals);

// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");

animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}

Output

Vector: [Dog, Horse, Cat]


New Vector: [Crocodile, Dog, Horse, Cat]

Access Vector Elements


 get(index) - returns an element specified by the index
 iterator() - returns an iterator object to sequentially access vector
elements
For example,

import java.util.Iterator;
import java.util.Vector;

class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");

// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);

// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}

Output

Element at index 2: Cat


Vector: Dog, Horse, Cat,

Remove Vector Elements


 remove(index) - removes an element from specified position
 removeAll() - removes all the elements
 clear() - removes all elements. It is more efficient than removeAll()

For example,

import java.util.Vector;

class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");

System.out.println("Initial Vector: " + animals);

// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);

// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output

Initial Vector: [Dog, Horse, Cat]


Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []

Others Vector Methods


Methods Descriptions

set() changes an element of the vector

size() returns the size of the vector

toArray() converts the vector into an array

toString() converts the vector into a String

contains() searches the vector for specified element and returns a boolean result

Java Stack Class


The Java collections framework has a class named Stack that provides the
functionality of the stack data structure.
The Stack class extends the Vector class.
Stack Implementation
In stack, elements are stored and accessed in Last In First Out manner.
That is, elements are added to the top of the stack and removed from the
top of the stack.
Creating a Stack
In order to create a stack, we must import the java.util.Stack package first.
Once we import the package, here is how we can create a stack in Java.

Stack<Type> stacks = new Stack<>();

Here, Type indicates the stack's type. For example,

// Create Integer type stack


Stack<Integer> stacks = new Stack<>();

// Create String type stack


Stack<String> stacks = new Stack<>();
Stack Methods
Since Stack extends the Vector class, it inherits all the
methods Vector. Besides these methods, the Stack class includes 5 more
methods that distinguish it from Vector .

push() Method
To add an element to the top of the stack, we use the push() method. For
example,
import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack


animals.push("Dog");
animals.push("Horse");
animals.push("Cat");

System.out.println("Stack: " + animals);


}
}
Run Code

Output

Stack: [Dog, Horse, Cat]


pop() Method
To remove an element from the top of the stack, we use the pop() method.
For example,
import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack


animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Initial Stack: " + animals);

// Remove element stacks


String element = animals.pop();
System.out.println("Removed Element: " + element);
}
}
Run Code

Output

Initial Stack: [Dog, Horse, Cat]


Removed Element: Cat

peek() Method
The peek() method returns an object from the top of the stack. For example,
import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack


animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);

// Access element from the top


String element = animals.peek();
System.out.println("Element at top: " + element);

}
}
Run Code

Output

Stack: [Dog, Horse, Cat]


Element at top: Cat

search() Method
To search an element in the stack, we use the search() method. It returns
the position of the element from the top of the stack. For example,
import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack


animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);

// Search an element
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
}
}
Output

Stack: [Dog, Horse, Cat]


Position of Horse: 2

empty() Method
To check whether a stack is empty or not, we use the empty() method. For
example,
import java.util.Stack;

class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();

// Add elements to Stack


animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);

// Check if stack is empty


boolean result = animals.empty();
System.out.println("Is the stack empty? " + result);
}
}
Run Code

Output

Stack: [Dog, Horse, Cat]


Is the stack empty? false
Java Queue Interface
The Queue interface of the Java collections framework provides the
functionality of the queue data structure. It extends the Collection interface.

Classes that Implement Queue


Since the Queue is an interface, we cannot provide the direct implementation
of it.
In order to use the functionalities of Queue , we need to use classes that
implement it:
 ArrayDeque
 LinkedList
 PriorityQueue

Working of Queue Data Structure


In queues, elements are stored and accessed in First In, First
Out manner. That is, elements are added from the behind and removed
from the front.
How to use Queue?
In Java, we must import java.util.Queue package in order to use Queue .

// LinkedList implementation of Queue


Queue<String> animal1 = new LinkedList<>();

// Array implementation of Queue


Queue<String> animal2 = new ArrayDeque<>();

// Priority Queue implementation of Queue


Queue<String> animal 3 = new PriorityQueue<>();

Here, we have created objects animal1 , animal2 and animal3 of


classes LinkedList , ArrayDeque and PriorityQueue respectively. These objects
can use the functionalities of the Queue interface.

Methods of Queue
The Queue interface includes all the methods of the Collection interface. It is
because Collection is the super interface of Queue .

Some of the commonly used methods of the Queue interface are:


 add() - Inserts the specified element into the queue. If the task is
successful, add() returns true , if not it throws an exception.
 offer() - Inserts the specified element into the queue. If the task is
successful, offer() returns true , if not it returns false .
 element() - Returns the head of the queue. Throws an exception if the
queue is empty.
 peek() - Returns the head of the queue. Returns null if the queue is empty.
 remove() - Returns and removes the head of the queue. Throws an
exception if the queue is empty.
 poll() - Returns and removes the head of the queue. Returns null if the
queue is empty.

Implementation of the Queue Interface


1. Implementing the LinkedList Class
import java.util.Queue;
import java.util.LinkedList;

class Main {

public static void main(String[] args) {


// Creating Queue using the LinkedList class
Queue<Integer> numbers = new LinkedList<>();

// offer elements to the Queue


numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);


}
}
Run Code

Output

Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]

2. Implementing the PriorityQueue Class


import java.util.Queue;
import java.util.PriorityQueue;

class Main {

public static void main(String[] args) {


// Creating Queue using the PriorityQueue class
Queue<Integer> numbers = new PriorityQueue<>();

// offer elements to the Queue


numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
System.out.println("Queue: " + numbers);

// Access elements of the Queue


int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);

System.out.println("Updated Queue: " + numbers);


}
}
Run Code

Output

Queue: [1, 5, 2]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 5]
Java PriorityQueue
The PriorityQueue class provides the functionality of the heap data
structure.
It implements the Queue interface.

Unlike normal queues, priority queue elements are retrieved in sorted


order.

Suppose, we want to retrieve elements in the ascending order. In this case,


the head of the priority queue will be the smallest element. Once this
element is retrieved, the next smallest element will be the head of the
queue.

It is important to note that the elements of a priority queue may not be


sorted. However, elements are always retrieved in sorted order.
Creating PriorityQueue
In order to create a priority queue, we must import
the java.util.PriorityQueue package. Once we import the package, here is
how we can create a priority queue in Java.

PriorityQueue<Integer> numbers = new PriorityQueue<>();

Here, we have created a priority queue without any arguments. In this


case, the head of the priority queue is the smallest element of the queue.
And elements are removed in ascending order from the queue.

Methods of PriorityQueue
The PriorityQueue class provides the implementation of all the methods
present in the Queue interface.

Insert Elements to PriorityQueue


 add() - Inserts the specified element to the queue. If the queue is full, it
throws an exception.
 offer() - Inserts the specified element to the queue. If the queue is full, it
returns false .

For example,

import java.util.PriorityQueue;

class Main {
public static void main(String[] args) {
// Creating a priority queue
PriorityQueue<Integer> numbers = new PriorityQueue<>();

// Using the add() method


numbers.add(4);
numbers.add(2);
System.out.println("PriorityQueue: " + numbers);

// Using the offer() method


numbers.offer(1);
System.out.println("Updated PriorityQueue: " + numbers);
}
}

Output

PriorityQueue: [2, 4]
Updated PriorityQueue: [1, 4, 2]

Here, we have created a priority queue named numbers . We have inserted 4


and 2 to the queue.
Although 4 is inserted before 2, the head of the queue is 2. It is because
the head of the priority queue is the smallest element of the queue.

We have then inserted 1 to the queue. The queue is now rearranged to


store the smallest element 1 to the head of the queue.

Access PriorityQueue Elements


To access elements from a priority queue, we can use the peek() method.
This method returns the head of the queue. For example,
import java.util.PriorityQueue;

class Main {
public static void main(String[] args) {

// Creating a priority queue


PriorityQueue<Integer> numbers = new PriorityQueue<>();
numbers.add(4);
numbers.add(2);
numbers.add(1);
System.out.println("PriorityQueue: " + numbers);

// Using the peek() method


int number = numbers.peek();
System.out.println("Accessed Element: " + number);
}
}
Run Code

Output

PriorityQueue: [1, 4, 2]
Accessed Element: 1

Remove PriorityQueue Elements


 remove() - removes the specified element from the queue
 poll() - returns and removes the head of the queue
For example,

import java.util.PriorityQueue;

class Main {
public static void main(String[] args) {

// Creating a priority queue


PriorityQueue<Integer> numbers = new PriorityQueue<>();
numbers.add(4);
numbers.add(2);
numbers.add(1);
System.out.println("PriorityQueue: " + numbers);

// Using the remove() method


boolean result = numbers.remove(2);
System.out.println("Is the element 2 removed? " + result);
// Using the poll() method
int number = numbers.poll();
System.out.println("Removed Element Using poll(): " + number);
}
}
Run Code

Output

PriorityQueue: [1, 4, 2]
Is the element 2 removed? true
Removed Element Using poll(): 1

Iterating Over a PriorityQueue


To iterate over the elements of a priority queue, we can use
the iterator() method. In order to use this method, we must import
the java.util.Iterator package. For example,
import java.util.PriorityQueue;
import java.util.Iterator;

class Main {
public static void main(String[] args) {

// Creating a priority queue


PriorityQueue<Integer> numbers = new PriorityQueue<>();
numbers.add(4);
numbers.add(2);
numbers.add(1);
System.out.print("PriorityQueue using iterator(): ");

//Using the iterator() method


Iterator<Integer> iterate = numbers.iterator();
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}

Output

PriorityQueue using iterator(): 1, 4, 2,

Other PriorityQueue Methods


Methods Descriptions

Searches the priority queue for the specified element. If the element is found, it returns
contains(element)
true , if not it returns false .

size() Returns the length of the priority queue.

toArray() Converts a priority queue to an array and returns it.

PriorityQueue Comparator
In all the examples above, priority queue elements are retrieved in the
natural order (ascending order). However, we can customize this ordering.

For this, we need to create our own comparator class that implements
the Comparator interface. For example,
import java.util.PriorityQueue;
import java.util.Comparator;
class Main {
public static void main(String[] args) {
// Creating a priority queue
PriorityQueue<Integer> numbers = new PriorityQueue<>(new
CustomComparator());
numbers.add(4);
numbers.add(2);
numbers.add(1);
numbers.add(3);
System.out.print("PriorityQueue: " + numbers);
}
}

class CustomComparator implements Comparator<Integer> {

@Override
public int compare(Integer number1, Integer number2) {
int value = number1.compareTo(number2);
// elements are sorted in reverse order
if (value > 0) {
return -1;
}
else if (value < 0) {
return 1;
}
else {
return 0;
}
}
}
Run Code

Output

PriorityQueue: [4, 3, 1, 2]

In the above example, we have created a priority queue


passing CustomComparator class as an argument.
The CustomComparator class implements the Comparator interface.
We then override the compare() method. The method now causes the head
of the element to be the largest number.
To learn more about the comparator, visit Java Comparator.
Java LinkedList
The LinkedList class of the Java collections framework provides the
functionality of the linked list data structure (doubly linkedlist).

Java Doubly LinkedList

Each element in a linked list is known as a node. It consists of 3 fields:


 Prev - stores an address of the previous element in the list. It is null for the
first element
 Next - stores an address of the next element in the list. It is null for the last
element
 Data - stores the actual data

Creating a Java LinkedList


Here is how we can create linked lists in Java:

LinkedList<Type> linkedList = new LinkedList<>();

Here, Type indicates the type of a linked list. For example,

// create Integer type linked list


LinkedList<Integer> linkedList = new LinkedList<>();

// create String type linked list


LinkedList<String> linkedList = new LinkedList<>();

Example: Create LinkedList in Java


import java.util.LinkedList;

class Main {
public static void main(String[] args){

// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// Add elements to LinkedList


animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);
}
}
Run Code

Output

LinkedList: [Dog, Cat, Cow]

In the above example, we have created a LinkedList named animals .

Here, we have used the add() method to add elements to the LinkedList.
We will learn more about the add() method later in this tutorial.

Working of a Java LinkedList


Elements in linked lists are not stored in sequence. Instead, they are
scattered and connected through links (Prev and Next).
Java LinkedList Implementation

Here we have 3 elements in a linked list.

 Dog - it is the first element that holds null as previous address and the
address of Cat as the next address
 Cat - it is the second element that holds an address of Dog as the previous
address and the address of Cow as the next address
 Cow - it is the last element that holds the address of Cat as the previous
address and null as the next element

Methods of Java LinkedList


LinkedList provides various methods that allow us to perform different
operations in linked lists. We will look at four commonly used LinkedList
Operators in this tutorial:
 Add elements

 Access elements

 Change elements

 Remove elements
1. Add elements to a LinkedList
We can use the add() method to add an element (node) at the end of the
LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// add() method without the index parameter


animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);

// add() method with the index parameter


animals.add(1, "Horse");
System.out.println("Updated LinkedList: " + animals);
}
}
Run Code

Output

LinkedList: [Dog, Cat, Cow]


Updated LinkedList: [Dog, Horse, Cat, Cow]

In the above example, we have created a LinkedList named animals . Here,


we have used the add() method to add elements to animals .

Notice the statement,

animals.add(1, "Horse");

Here, we have used the index number parameter. It is an optional


parameter that specifies the position where the new element is added.

2. Access LinkedList elements


The get() method of the LinkedList class is used to access an element
from the LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in the linked list


languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
System.out.println("LinkedList: " + languages);

// get the element from the linked list


String str = languages.get(1);
System.out.print("Element at index 1: " + str);
}
}
Run Code

Output

LinkedList: [Python, Java, JavaScript]


Element at index 1: Java

In the above example, we have used the get() method with parameter 1.
Here, the method returns the element at index 1.
We can also access elements of the LinkedList using the iterator() and
the listIterator() method.

3. Change Elements of a LinkedList


The set() method of LinkedList class is used to change elements of the
LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
// add elements in the linked list
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java");
System.out.println("LinkedList: " + languages);

// change elements at index 3


languages.set(3, "C");
System.out.println("Updated LinkedList: " + languages);
}
}
Run Code

Output

LinkedList: [Java, Python, JavaScript, Java]


Updated LinkedList: [Java, Python, JavaScript, C]

In the above example, we have created a LinkedList named languages.


Notice the line,

languages.set(3, "Kotlin");

Here, the set() method changes the element at index 3 to Kotlin .

4. Remove element from a LinkedList


The remove() method of the LinkedList class is used to remove an element
from the LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in LinkedList


languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Kotlin");
System.out.println("LinkedList: " + languages);

// remove elements from index 1


String str = languages.remove(1);
System.out.println("Removed Element: " + str);

System.out.println("Updated LinkedList: " + languages);


}
}
Run Code

Output

LinkedList: [Java, Python, JavaScript, Kotlin]


Removed Element: Python
New LinkedList: [Java, JavaScript, Kotlin]

Here, the remove() method takes the index number as the parameter. And,
removes the element specified by the index number.

Other Methods
Methods Description

contains() checks if the LinkedList contains the element

indexOf() returns the index of the first occurrence of the element

lastIndexOf() returns the index of the last occurrence of the element

clear() removes all the elements of the LinkedList


iterator() returns an iterator to iterate over LinkedList

LinkedList as Deque and Queue


Since the LinkedList class also implements the Queue and
the Deque interface, it can implement methods of these interfaces as well.
Here are some of the commonly used methods:
Methods Descriptions

addFirst() adds the specified element at the beginning of the linked list

addLast() adds the specified element at the end of the linked list

getFirst() returns the first element

getLast() returns the last element

removeFirst() removes the first element

removeLast() removes the last element

peek() returns the first element (head) of the linked list

poll() returns and removes the first element from the linked list

offer() adds the specified element at the end of the linked list
Example: Java LinkedList as Queue
import java.util.LinkedList;
import java.util.Queue;

class Main {
public static void main(String[] args) {
Queue<String> languages = new LinkedList<>();

// add elements
languages.add("Python");
languages.add("Java");
languages.add("C");
System.out.println("LinkedList: " + languages);

// access the first element


String str1 = languages.peek();
System.out.println("Accessed Element: " + str1);

// access and remove the first element


String str2 = languages.poll();
System.out.println("Removed Element: " + str2);
System.out.println("LinkedList after poll(): " + languages);

// add element at the end


languages.offer("Swift");
System.out.println("LinkedList after offer(): " + languages);
}
}
Run Code

Output

LinkedList: [Python, Java, C]


Accessed Element: Python
Removed Element: Python
LinkedList after poll(): [Java, C]
LinkedList after offer(): [Java, C, Swift]
Example: LinkedList as Deque
import java.util.LinkedList;
import java.util.Deque;

class Main {
public static void main(String[] args){
Deque<String> animals = new LinkedList<>();

// add element at the beginning


animals.add("Cow");
System.out.println("LinkedList: " + animals);

animals.addFirst("Dog");
System.out.println("LinkedList after addFirst(): " + animals);

// add elements at the end


animals.addLast("Zebra");
System.out.println("LinkedList after addLast(): " + animals);

// remove the first element


animals.removeFirst();
System.out.println("LinkedList after removeFirst(): " + animals);

// remove the last element


animals.removeLast();
System.out.println("LinkedList after removeLast(): " + animals);
}
}
Run Code

Output

LinkedList: [Cow]
LinkedList after addFirst(): [Dog, Cow]
LinkedList after addLast(): [Dog, Cow, Zebra]
LinkedList after removeFirst(): [Cow, Zebra]
LinkedList after removeLast(): [Cow]
Iterating through LinkedList
We can use the Java for-each loop to iterate through LinkedList. For
example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
// Creating a linked list
LinkedList<String> animals = new LinkedList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("LinkedList: " + animals);

// Using forEach loop


System.out.println("Accessing linked list elements:");
for(String animal: animals) {
System.out.print(animal);
System.out.print(", ");
}
}
}
Run Code

Output

LinkedList: [Cow, Cat, Dog]


Accessing linked list elements:
Cow, Cat, Dog,

LinkedList Vs. ArrayList


Both the Java ArrayList and LinkedList implements the List interface of
the Collections framework. However, there exists some difference between
them.
LinkedList ArrayList

Implements List , Queue , and Deque interfaces. Implements List interface.

Stores 3 values (previous address, data, and next


Stores a single value in a single position.
address) in a single position.

Provides the doubly-linked list implementation. Provides a resizable array implementation.

Whenever an element is added, prev and next Whenever an element is added, all elements
address are changed. after that position are shifted.

To access an element, we need to iterate from the


Can randomly access elements using indexes.
beginning to the element.

Note: We can also create a LinkedList using interfaces in Java. For


example,

// create linkedlist using List


List<String> animals1 = new LinkedList<>();

// creating linkedlist using Queue


Queue<String> animals2 = new LinkedList<>();

// creating linkedlist using Deque


Deque<String> animals3 = new LinkedList<>();

Here, if the LinkedList is created using one interface, then we cannot use
methods provided by other interfaces. That is, animals1 cannot use methods
specific to Queue and Deque interfaces.

Java Deque Interface


The Deque interface of the Java collections framework provides the
functionality of a double-ended queue. It extends the Queue interface.

Working of Deque
In a regular queue, elements are added from the rear and removed from
the front. However, in a deque, we can insert and remove elements from
both front and rear.

Classes that implement Deque


In order to use the functionalities of the Deque interface, we need to use
classes that implement it:
 ArrayDeque
 LinkedList
How to use Deque?
In Java, we must import the java.util.Deque package to use Deque .

// Array implementation of Deque


Deque<String> animal1 = new ArrayDeque<>();

// LinkedList implementation of Deque


Deque<String> animal2 = new LinkedList<>();

Here, we have created objects animal1 and animal2 of


classes ArrayDeque and LinkedList , respectively. These objects can use the
functionalities of the Deque interface.

Methods of Deque
Since Deque extends the Queue interface, it inherits all the methods of the
Queue interface.
Besides methods available in the Queue interface, the Deque interface also
includes the following methods:
 addFirst() - Adds the specified element at the beginning of the deque.
Throws an exception if the deque is full.
 addLast() - Adds the specified element at the end of the deque. Throws an
exception if the deque is full.
 offerFirst() - Adds the specified element at the beginning of the deque.
Returns false if the deque is full.
 offerLast() - Adds the specified element at the end of the deque.
Returns false if the deque is full.
 getFirst() - Returns the first element of the deque. Throws an exception if
the deque is empty.
 getLast() - Returns the last element of the deque. Throws an exception if
the deque is empty.
 peekFirst() - Returns the first element of the deque. Returns null if the
deque is empty.
 peekLast() - Returns the last element of the deque. Returns null if the
deque is empty.
 removeFirst() - Returns and removes the first element of the deque.
Throws an exception if the deque is empty.
 removeLast() - Returns and removes the last element of the deque.
Throws an exception if the deque is empty.
 pollFirst() - Returns and removes the first element of the deque.
Returns null if the deque is empty.
 pollLast() - Returns and removes the last element of the deque.
Returns null if the deque is empty.

Deque as Stack Data Structure


The Stack class of the Java Collections framework provides the
implementation of the stack.
However, it is recommended to use Deque as a stack instead of the Stack
class. It is because methods of Stack are synchronized.
Here are the methods the Deque interface provides to implement stack:
 push() - adds an element at the beginning of deque
 pop() - removes an element from the beginning of deque
 peek() - returns an element from the beginning of deque
Implementation of Deque in ArrayDeque
Class
import java.util.Deque;
import java.util.ArrayDeque;

class Main {

public static void main(String[] args) {


// Creating Deque using the ArrayDeque class
Deque<Integer> numbers = new ArrayDeque<>();

// add elements to the Deque


numbers.offer(1);
numbers.offerLast(2);
numbers.offerFirst(3);
System.out.println("Deque: " + numbers);

// Access elements of the Deque


int firstElement = numbers.peekFirst();
System.out.println("First Element: " + firstElement);

int lastElement = numbers.peekLast();


System.out.println("Last Element: " + lastElement);

// Remove elements from the Deque


int removedNumber1 = numbers.pollFirst();
System.out.println("Removed First Element: " + removedNumber1);

int removedNumber2 = numbers.pollLast();


System.out.println("Removed Last Element: " + removedNumber2);

System.out.println("Updated Deque: " + numbers);


}
}
Run Code

Output

Deque: [3, 1, 2]
First Element: 3
Last Element: 2
Removed First Element: 3
Removed Last Element: 2
Updated Deque: [1]

Java LinkedList
The LinkedList class of the Java collections framework provides the
functionality of the linked list data structure (doubly linkedlist).

Java Doubly LinkedList

Each element in a linked list is known as a node. It consists of 3 fields:


 Prev - stores an address of the previous element in the list. It is null for the
first element
 Next - stores an address of the next element in the list. It is null for the last
element
 Data - stores the actual data

Creating a Java LinkedList


Here is how we can create linked lists in Java:

LinkedList<Type> linkedList = new LinkedList<>();

Here, Type indicates the type of a linked list. For example,


// create Integer type linked list
LinkedList<Integer> linkedList = new LinkedList<>();

// create String type linked list


LinkedList<String> linkedList = new LinkedList<>();

Example: Create LinkedList in Java


import java.util.LinkedList;

class Main {
public static void main(String[] args){

// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// Add elements to LinkedList


animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);
}
}
Run Code

Output

LinkedList: [Dog, Cat, Cow]

In the above example, we have created a LinkedList named animals .

Here, we have used the add() method to add elements to the LinkedList.
We will learn more about the add() method later in this tutorial.
Working of a Java LinkedList
Elements in linked lists are not stored in sequence. Instead, they are
scattered and connected through links (Prev and Next).

Java LinkedList Implementation

Here we have 3 elements in a linked list.

 Dog - it is the first element that holds null as previous address and the
address of Cat as the next address
 Cat - it is the second element that holds an address of Dog as the previous
address and the address of Cow as the next address
 Cow - it is the last element that holds the address of Cat as the previous
address and null as the next element
To learn more, visit the LinkedList Data Structure.

Methods of Java LinkedList


LinkedList provides various methods that allow us to perform different
operations in linked lists. We will look at four commonly used LinkedList
Operators in this tutorial:
 Add elements
 Access elements

 Change elements

 Remove elements

1. Add elements to a LinkedList


We can use the add() method to add an element (node) at the end of the
LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();

// add() method without the index parameter


animals.add("Dog");
animals.add("Cat");
animals.add("Cow");
System.out.println("LinkedList: " + animals);

// add() method with the index parameter


animals.add(1, "Horse");
System.out.println("Updated LinkedList: " + animals);
}
}
Run Code

Output

LinkedList: [Dog, Cat, Cow]


Updated LinkedList: [Dog, Horse, Cat, Cow]

In the above example, we have created a LinkedList named animals . Here,


we have used the add() method to add elements to animals .

Notice the statement,


animals.add(1, "Horse");

Here, we have used the index number parameter. It is an optional


parameter that specifies the position where the new element is added.
To learn more about adding elements to LinkedList, visit Java program to
add elements to LinkedList.

2. Access LinkedList elements


The get() method of the LinkedList class is used to access an element
from the LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in the linked list


languages.add("Python");
languages.add("Java");
languages.add("JavaScript");
System.out.println("LinkedList: " + languages);

// get the element from the linked list


String str = languages.get(1);
System.out.print("Element at index 1: " + str);
}
}
Run Code

Output

LinkedList: [Python, Java, JavaScript]


Element at index 1: Java

In the above example, we have used the get() method with parameter 1.
Here, the method returns the element at index 1.
We can also access elements of the LinkedList using the iterator() and
the listIterator() method. To learn more, visit the Java program to access
elements of LinkedList.

3. Change Elements of a LinkedList


The set() method of LinkedList class is used to change elements of the
LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in the linked list


languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Java");
System.out.println("LinkedList: " + languages);

// change elements at index 3


languages.set(3, "Kotlin");
System.out.println("Updated LinkedList: " + languages);
}
}
Run Code

Output

LinkedList: [Java, Python, JavaScript, Java]


Updated LinkedList: [Java, Python, JavaScript, Kotlin]

In the above example, we have created a LinkedList named languages.


Notice the line,

languages.set(3, "Kotlin");
Here, the set() method changes the element at index 3 to Kotlin .

4. Remove element from a LinkedList


The remove() method of the LinkedList class is used to remove an element
from the LinkedList. For example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();

// add elements in LinkedList


languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
languages.add("Kotlin");
System.out.println("LinkedList: " + languages);

// remove elements from index 1


String str = languages.remove(1);
System.out.println("Removed Element: " + str);

System.out.println("Updated LinkedList: " + languages);


}
}
Run Code

Output

LinkedList: [Java, Python, JavaScript, Kotlin]


Removed Element: Python
New LinkedList: [Java, JavaScript, Kotlin]

Here, the remove() method takes the index number as the parameter. And,
removes the element specified by the index number.
To learn more about removing elements from the linkedlist, visit the Java
program to remove elements from LinkedList..
Other Methods
Methods Description

contains() checks if the LinkedList contains the element

indexOf() returns the index of the first occurrence of the element

lastIndexOf() returns the index of the last occurrence of the element

clear() removes all the elements of the LinkedList

iterator() returns an iterator to iterate over LinkedList

LinkedList as Deque and Queue


Since the LinkedList class also implements the Queue and
the Deque interface, it can implement methods of these interfaces as well.
Here are some of the commonly used methods:
Methods Descriptions

addFirst() adds the specified element at the beginning of the linked list

addLast() adds the specified element at the end of the linked list
getFirst() returns the first element

getLast() returns the last element

removeFirst() removes the first element

removeLast() removes the last element

peek() returns the first element (head) of the linked list

poll() returns and removes the first element from the linked list

offer() adds the specified element at the end of the linked list

Example: Java LinkedList as Queue


import java.util.LinkedList;
import java.util.Queue;

class Main {
public static void main(String[] args) {
Queue<String> languages = new LinkedList<>();

// add elements
languages.add("Python");
languages.add("Java");
languages.add("C");
System.out.println("LinkedList: " + languages);

// access the first element


String str1 = languages.peek();
System.out.println("Accessed Element: " + str1);

// access and remove the first element


String str2 = languages.poll();
System.out.println("Removed Element: " + str2);
System.out.println("LinkedList after poll(): " + languages);

// add element at the end


languages.offer("Swift");
System.out.println("LinkedList after offer(): " + languages);
}
}
Run Code

Output

LinkedList: [Python, Java, C]


Accessed Element: Python
Removed Element: Python
LinkedList after poll(): [Java, C]
LinkedList after offer(): [Java, C, Swift]

Example: LinkedList as Deque


import java.util.LinkedList;
import java.util.Deque;

class Main {
public static void main(String[] args){
Deque<String> animals = new LinkedList<>();

// add element at the beginning


animals.add("Cow");
System.out.println("LinkedList: " + animals);

animals.addFirst("Dog");
System.out.println("LinkedList after addFirst(): " + animals);

// add elements at the end


animals.addLast("Zebra");
System.out.println("LinkedList after addLast(): " + animals);

// remove the first element


animals.removeFirst();
System.out.println("LinkedList after removeFirst(): " + animals);

// remove the last element


animals.removeLast();
System.out.println("LinkedList after removeLast(): " + animals);
}
}
Run Code

Output

LinkedList: [Cow]
LinkedList after addFirst(): [Dog, Cow]
LinkedList after addLast(): [Dog, Cow, Zebra]
LinkedList after removeFirst(): [Cow, Zebra]
LinkedList after removeLast(): [Cow]

Iterating through LinkedList


We can use the Java for-each loop to iterate through LinkedList. For
example,
import java.util.LinkedList;

class Main {
public static void main(String[] args) {
// Creating a linked list
LinkedList<String> animals = new LinkedList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("LinkedList: " + animals);

// Using forEach loop


System.out.println("Accessing linked list elements:");
for(String animal: animals) {
System.out.print(animal);
System.out.print(", ");
}
}
}
Run Code

Output
LinkedList: [Cow, Cat, Dog]
Accessing linked list elements:
Cow, Cat, Dog,

LinkedList Vs. ArrayList


Both the Java ArrayList and LinkedList implements the List interface of
the Collections framework. However, there exists some difference between
them.
LinkedList ArrayList

Implements List , Queue , and Deque interfaces. Implements List interface.

Stores 3 values (previous address, data, and next


Stores a single value in a single position.
address) in a single position.

Provides the doubly-linked list implementation. Provides a resizable array implementation.

Whenever an element is added, prev and next address Whenever an element is added, all elements after th
are changed. position are shifted.

To access an element, we need to iterate from the


Can randomly access elements using indexes.
beginning to the element.

Note: We can also create a LinkedList using interfaces in Java


Java Set Interface
The Set interface of the Java Collections framework provides the features
of the mathematical set in Java. It extends the Collection interface.
Unlike the List interface, sets cannot contain duplicate elements

Classes that implement Set


Since Set is an interface, we cannot create objects from it.
In order to use functionalities of the Set interface, we can use these
classes:
 HashSet
 LinkedHashSet
 EnumSet
 TreeSet
These classes are defined in the Collections framework and implement
the Set interface.

Interfaces that extend Set


The Set interface is also extended by these subinterfaces:
 SortedSet
 NavigableSet
How to use Set?
In Java, we must import java.util.Set package in order to use Set .

// Set implementation using HashSet


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

Here, we have created a Set called animals . We have used the HashSet class
to implement the Set interface.

Methods of Set
The Set interface includes all the methods of the Collection interface. It's
because Collection is a super interface of Set .

Some of the commonly used methods of the Collection interface that's also
available in the Set interface are:
 add() - adds the specified element to the set
 addAll() - adds all the elements of the specified collection to the set
 iterator() - returns an iterator that can be used to access elements of the
set sequentially
 remove() - removes the specified element from the set
 removeAll() - removes all the elements from the set that is present in
another specified set
 retainAll() - retains all the elements in the set that are also present in
another specified set
 clear() - removes all the elements from the set
 size() - returns the length (number of elements) of the set
 toArray() - returns an array containing all the elements of the set
 contains() - returns true if the set contains the specified element
 containsAll() - returns true if the set contains all the elements of the
specified collection

Set Operations
The Java Set interface allows us to perform basic mathematical set
operations like union, intersection, and subset.
 Union - to get the union of two sets x and y , we can use x.addAll(y)

 Intersection - to get the intersection of two sets x and y , we can


use x.retainAll(y)

 Subset - to check if x is a subset of y , we can use y.containsAll(x)

Implementation of the Set Interface


1. Implementing HashSet Class
import java.util.Set;
import java.util.HashSet;

class Main {

public static void main(String[] args) {


// Creating a set using the HashSet class
Set<Integer> set1 = new HashSet<>();

// Add elements to the set1


set1.add(2);
set1.add(3);
System.out.println("Set1: " + set1);

// Creating another set using the HashSet class


Set<Integer> set2 = new HashSet<>();

// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);

// Union of two sets


set2.addAll(set1);
System.out.println("Union is: " + set2);
}
}
Run Code

Output

Set1: [2, 3]
Set2: [1, 2]
Union is: [1, 2, 3]

2. Implementing TreeSet Class


import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;

class Main {

public static void main(String[] args) {


// Creating a set using the TreeSet class
Set<Integer> numbers = new TreeSet<>();

// Add elements to the set


numbers.add(2);
numbers.add(3);
numbers.add(1);
System.out.println("Set using TreeSet: " + numbers);

// Access Elements using iterator()


System.out.print("Accessing elements using iterator(): ");
Iterator<Integer> iterate = numbers.iterator();
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}

}
}
Run Code

Output

Set using TreeSet: [1, 2, 3]


Accessing elements using iterator(): 1, 2, 3,

Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It
inherits the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the
basis of their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Difference between List and Set


A list can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class


The HashSet class extends AbstractSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

Java HashSet Class


The HashSet class of the Java Collections framework provides the
functionalities of the hash table data structure.
It implements the Set interface.
Creating a HashSet
In order to create a hash set, we must import the java.util.HashSet package
first.
Once we import the package, here is how we can create hash sets in Java.

// HashSet with 8 capacity and 0.6 load factor


HashSet<Integer> numbers = new HashSet<>(8, 0.6);

Here, we have created a hash set named numbers .

Notice, the part new HashSet<>(8, 0.6) . Here, the first parameter
is capacity, and the second parameter is loadFactor.
 capacity - The capacity of this hash set is 8. Meaning, it can store 8
elements.
 loadFactor - The load factor of this hash set is 0.6. This means, whenever
our hash set is filled by 60%, the elements are moved to a new hash table
of double the size of the original hash table.
Default capacity and load factor
It's possible to create a hash table without defining its capacity and load
factor. For example,

// HashSet with default capacity and load factor


HashSet<Integer> numbers1 = new HashSet<>();

By default,

 the capacity of the hash set will be 16

 the load factor will be 0.75

Methods of HashSet
The HashSet class provides various methods that allow us to perform
various operations on the set.

Insert Elements to HashSet


 add() - inserts the specified element to the set
 addAll() - inserts all the elements of the specified collection to the set
For example,

import java.util.HashSet;

class Main {
public static void main(String[] args) {
HashSet<Integer> evenNumber = new HashSet<>();

// Using add() method


evenNumber.add(2);
evenNumber.add(4);
evenNumber.add(6);
System.out.println("HashSet: " + evenNumber);

HashSet<Integer> numbers = new HashSet<>();

// Using addAll() method


numbers.addAll(evenNumber);
numbers.add(5);
System.out.println("New HashSet: " + numbers);
}
}
Run Code

Output

HashSet: [2, 4, 6]
New HashSet: [2, 4, 5, 6]

Access HashSet Elements


To access the elements of a hash set, we can use the iterator() method.
In order to use this method, we must import the java.util.Iterator package.
For example,
import java.util.HashSet;
import java.util.Iterator;

class Main {
public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("HashSet: " + numbers);

// Calling iterator() method


Iterator<Integer> iterate = numbers.iterator();
System.out.print("HashSet using Iterator: ");
// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Run Code

Output

HashSet: [2, 5, 6]
HashSet using Iterator: 2, 5, 6,

Remove Elements
 remove() - removes the specified element from the set
 removeAll() - removes all the elements from the set
For example,

import java.util.HashSet;

class Main {
public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("HashSet: " + numbers);

// Using remove() method


boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);

boolean value2 = numbers.removeAll(numbers);


System.out.println("Are all elements removed? " + value2);
}
}
Run Code
Output

HashSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true

Set Operations
The various methods of the HashSet class can also be used to perform
various set operations.

Union of Sets
To perform the union between two sets, we can use the addAll() method.
For example,
import java.util.HashSet;

class Main {
public static void main(String[] args) {
HashSet<Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("HashSet1: " + evenNumbers);

HashSet<Integer> numbers = new HashSet<>();


numbers.add(1);
numbers.add(3);
System.out.println("HashSet2: " + numbers);

// Union of two set


numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);
}
}

Run Code

Output

HashSet1: [2, 4]
HashSet2: [1, 3]
Union is: [1, 2, 3, 4]

Intersection of Sets
To perform the intersection between two sets, we can use
the retainAll() method. For example
import java.util.HashSet;

class Main {
public static void main(String[] args) {
HashSet<Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("HashSet1: " + primeNumbers);

HashSet<Integer> evenNumbers = new HashSet<>();


evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("HashSet2: " + evenNumbers);

// Intersection of two sets


evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection is: " + evenNumbers);
}
}
Run Code

Output

HashSet1: [2, 3]
HashSet2: [2, 4]
Intersection is: [2]

Difference of Sets
To calculate the difference between the two sets, we can use
the removeAll() method. For example,
import java.util.HashSet;

class Main {
public static void main(String[] args) {
HashSet<Integer> primeNumbers = new HashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
System.out.println("HashSet1: " + primeNumbers);

HashSet<Integer> oddNumbers = new HashSet<>();


oddNumbers.add(1);
oddNumbers.add(3);
oddNumbers.add(5);
System.out.println("HashSet2: " + oddNumbers);

// Difference between HashSet1 and HashSet2


primeNumbers.removeAll(oddNumbers);
System.out.println("Difference : " + primeNumbers);
}
}
Run Code

Output

HashSet1: [2, 3, 5]
HashSet2: [1, 3, 5]
Difference: [2]
Subset
To check if a set is a subset of another set or not, we can use
the containsAll() method. For example,
import java.util.HashSet;

class Main {
public static void main(String[] args) {
HashSet<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("HashSet1: " + numbers);

HashSet<Integer> primeNumbers = new HashSet<>();


primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("HashSet2: " + primeNumbers);

// Check if primeNumbers is a subset of numbers


boolean result = numbers.containsAll(primeNumbers);
System.out.println("Is HashSet2 is subset of HashSet1? " + result);
}
}
Run Code

Output

HashSet1: [1, 2, 3, 4]
HashSet2: [2, 3]
Is HashSet2 is a subset of HashSet1? true

Other Methods Of HashSet


Method Description
clone() Creates a copy of the HashSet

contains() Searches the HashSet for the specified element and returns a boolean result

isEmpty() Checks if the HashSet is empty

size() Returns the size of the HashSet

clear() Removes all the elements from the HashSet

Why 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.

Note: HashSet is not synchronized. That is if multiple threads access the


hash set at the same time and one of the threads modifies the hash set.
Then it must be externally synchronized.
Java LinkedHashSet
The LinkedHashSet class of the Java collections framework provides
functionalities of both the hashtable and the linked list data structure.
It implements the Set interface.

Elements of LinkedHashSet are stored in hash tables similar to HashSet.


However, linked hash sets maintain a doubly-linked list internally for all of
its elements. The linked list defines the order in which elements are
inserted in hash tables.

Create a LinkedHashSet
In order to create a linked hash set, we must import
the java.util.LinkedHashSet package first.
Once we import the package, here is how we can create linked hash sets in
Java.

// LinkedHashSet with 8 capacity and 0.75 load factor


LinkedHashSet<Integer> numbers = new LinkedHashSet<>(8, 0.75);
Here, we have created a linked hash set named numbers .

Notice, the part new LinkedHashSet<>(8, 0.75) . Here, the first parameter
is capacity and the second parameter is loadFactor.
 capacity - The capacity of this hash set is 8. Meaning, it can store 8
elements.
 loadFactor - The load factor of this hash set is 0.6. This means, whenever
our hash table is filled by 60%, the elements are moved to a new hash
table of double the size of the original hash table.
Default capacity and load factor
It's possible to create a linked hash set without defining its capacity and
load factor. For example,

// LinkedHashSet with default capacity and load factor


LinkedHashSet<Integer> numbers1 = new LinkedHashSet<>();

By default,

 the capacity of the linked hash set will be 16

 the load factor will be 0.75

Creating LinkedHashSet from Other


Collections
Here is how we can create a linked hash set containing all the elements of
other collections.

import java.util.LinkedHashSet;
import java.util.ArrayList;

class Main {
public static void main(String[] args) {
// Creating an arrayList of even numbers
ArrayList<Integer> evenNumbers = new ArrayList<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("ArrayList: " + evenNumbers);

// Creating a LinkedHashSet from an ArrayList


LinkedHashSet<Integer> numbers = new LinkedHashSet<>(evenNumbers);
System.out.println("LinkedHashSet: " + numbers);
}
}

Run Code

Output

ArrayList: [2, 4]
LinkedHashSet: [2, 4]

Methods of LinkedHashSet
The LinkedHashSet class provides methods that allow us to perform various
operations on the linked hash set.

Insert Elements to LinkedHashSet


 add() - inserts the specified element to the linked hash set
 addAll() - inserts all the elements of the specified collection to the linked
hash set
For example,

import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> evenNumber = new LinkedHashSet<>();

// Using add() method


evenNumber.add(2);
evenNumber.add(4);
evenNumber.add(6);
System.out.println("LinkedHashSet: " + evenNumber);

LinkedHashSet<Integer> numbers = new LinkedHashSet<>();

// Using addAll() method


numbers.addAll(evenNumber);
numbers.add(5);
System.out.println("New LinkedHashSet: " + numbers);
}
}
Run Code

Output

LinkedHashSet: [2, 4, 6]
New LinkedHashSet: [2, 4, 6, 5]

Access LinkedHashSet Elements


To access the elements of a linked hash set, we can use
the iterator()method. In order to use this method, we must import
the java.util.Iterator package. For example,
import java.util.LinkedHashSet;
import java.util.Iterator;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("LinkedHashSet: " + numbers);
// Calling the iterator() method
Iterator<Integer> iterate = numbers.iterator();

System.out.print("LinkedHashSet using Iterator: ");

// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Run Code

Output

LinkedHashSet: [2, 5, 6]
LinkedHashSet using Iterator: 2, 5, 6,

Note:
 hasNext() returns true if there is a next element in the linked hash set
 next() returns the next element in the linked hash set

Remove Elements from HashSet


 remove() - removes the specified element from the linked hash set
 removeAll() - removes all the elements from the linked hash set
For example,

import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("LinkedHashSet: " + numbers);
// Using the remove() method
boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);

boolean value2 = numbers.removeAll(numbers);


System.out.println("Are all elements removed? " + value2);
}
}
Run Code

Output

LinkedHashSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true

Set Operations
The various methods of the LinkedHashSet class can also be used to perform
various set operations.

Union of Sets
Two perform the union between two sets, we can use the addAll() method.
For example,
import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("LinkedHashSet1: " + evenNumbers);
LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
numbers.add(1);
numbers.add(3);
System.out.println("LinkedHashSet2: " + numbers);

// Union of two set


numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);
}
}
Run Code

Output

LinkedHashSet1: [2, 4]
LinkedHashSet2: [1, 3]
Union is: [1, 3, 2, 4]

Intersection of Sets
To perform the intersection between two sets, we can use
the retainAll() method. For example
import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("LinkedHashSet1: " + primeNumbers);

LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();


evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("LinkedHashSet2: " + evenNumbers);

// Intersection of two sets


evenNumbers.retainAll(primeNumbers);
System.out.println("Intersection is: " + evenNumbers);
}
}
Run Code

Output

LinkedHashSet1: [2, 3]
LinkedHashSet2: [2, 4]
Intersection is: [2]

Difference of Sets
To calculate the difference between the two sets, we can use
the removeAll() method. For example,
import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
System.out.println("LinkedHashSet1: " + primeNumbers);

LinkedHashSet<Integer> oddNumbers = new LinkedHashSet<>();


oddNumbers.add(1);
oddNumbers.add(3);
oddNumbers.add(5);
System.out.println("LinkedHashSet2: " + oddNumbers);

// Difference between LinkedHashSet1 and LinkedHashSet2


primeNumbers.removeAll(oddNumbers);
System.out.println("Difference : " + primeNumbers);
}
}
Run Code

Output

LinkedHashSet1: [2, 3, 5]
LinkedHashSet2: [1, 3, 5]
Difference: [2]

Subset
To check if a set is a subset of another set or not, we can use
the containsAll() method. For example,
import java.util.LinkedHashSet;

class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> numbers = new LinkedHashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("LinkedHashSet1: " + numbers);

LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();


primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("LinkedHashSet2: " + primeNumbers);

// Check if primeNumbers is a subset of numbers


boolean result = numbers.containsAll(primeNumbers);
System.out.println("Is LinkedHashSet2 is subset of LinkedHashSet1? " +
result);
}
}
Run Code

Output

LinkedHashSet1: [1, 2, 3, 4]
LinkedHashSet2: [2, 3]
Is LinkedHashSet2 is a subset of LinkedHashSet1? true
Other Methods Of LinkedHashSet
Method Description

clone() Creates a copy of the LinkedHashSet

contains() Searches the LinkedHashSet for the specified element and returns a boolean result

isEmpty() Checks if the LinkedHashSet is empty

size() Returns the size of the LinkedHashSet

clear() Removes all the elements from the LinkedHashSet

LinkedHashSet Vs. HashSet


Both LinkedHashSet and HashSet implements the Set interface. However,
there exist some differences between them.
 LinkedHashSet maintains a linked list internally. Due to this, it maintains the
insertion order of its elements.
 The LinkedHashSet class requires more storage than HashSet . This is
because LinkedHashSet maintains linked lists internally.
 The performance of LinkedHashSet is slower than HashSet . It is because of
linked lists present in LinkedHashSet .
LinkedHashSet Vs. TreeSet
Here are the major differences between LinkedHashSet and TreeSet :

 The TreeSet class implements the SortedSet interface. That's why elements
in a tree set are sorted. However, the LinkedHashSet class only maintains the
insertion order of its elements.
 A TreeSet is usually slower than a LinkedHashSet . It is because whenever an
element is added to a TreeSet , it has to perform the sorting operation.
 LinkedHashSet allows the insertion of null values. However, we cannot insert
a null value to TreeSet .

Java SortedSet Interface


The SortedSet interface of the Java collections framework is used to store
elements with some order in a set.
It extends the Set interface.
Class that implements SortedSet
In order to use the functionalities of the SortedSet interface, we need to use
the TreeSet class that implements it.

How to use SortedSet?


To use SortedSet , we must import the java.util.SortedSet package first.

// SortedSet implementation by TreeSet class


SortedSet<String> animals = new TreeSet<>();

We have created a sorted set called animals using the TreeSet class.
Here we have used no arguments to create a sorted set. Hence the set will
be sorted naturally.
Methods of SortedSet
The SortedSet interface includes all the methods of the Set interface. It's
because Set is a super interface of SortedSet .

Besides methods included in the Set interface, the SortedSet interface also
includes these methods:
 comparator() - returns a comparator that can be used to order elements in
the set
 first() - returns the first element of the set
 last() - returns the last element of the set
 headSet(element) - returns all the elements of the set before the specified
element
 tailSet(element) - returns all the elements of the set after the specified
element including the specified element
 subSet(element1, element2) - returns all the elements between
the element1 and element2 including element1

Implementation of SortedSet in TreeSet


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

class Main {

public static void main(String[] args) {


// Creating SortedSet using the TreeSet
SortedSet<Integer> numbers = new TreeSet<>();

// Insert elements to the set


numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("SortedSet: " + numbers);

// Access the element


int firstNumber = numbers.first();
System.out.println("First Number: " + firstNumber);

int lastNumber = numbers.last();


System.out.println("Last Number: " + lastNumber);

// Remove elements
boolean result = numbers.remove(2);
System.out.println("Is the number 2 removed? " + result);
}
}
Run Code

Output

SortedSet: [1, 2, 3, 4]
First Number: 1
Last Number: 4
Is the number 2 removed? true

To learn more about TreeSet , visit Java TreeSet.

Now that we know about the SortedSet interface, we will learn about its
implementation using the TreeSet class.

Java TreeSet
The TreeSet class of the Java collections framework provides the
functionality of a tree data structure.
It extends the NavigableSet interface.
Creating a TreeSet
In order to create a tree set, we must import the java.util.TreeSet package
first.
Once we import the package, here is how we can create a TreeSet in Java.

TreeSet<Integer> numbers = new TreeSet<>();

Here, we have created a TreeSet without any arguments. In this case, the
elements in TreeSet are sorted naturally (ascending order).
However, we can customize the sorting of elements by using
the Comparator interface. We will learn about it later in this tutorial.
Methods of TreeSet
The TreeSet class provides various methods that allow us to perform
various operations on the set.

Insert Elements to TreeSet


 add() - inserts the specified element to the set
 addAll() - inserts all the elements of the specified collection to the set
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {

TreeSet<Integer> evenNumbers = new TreeSet<>();

// Using the add() method


evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.add(6);
System.out.println("TreeSet: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);

// Using the addAll() method


numbers.addAll(evenNumbers);
System.out.println("New TreeSet: " + numbers);
}
}
Run Code

Output

TreeSet: [2, 4, 6]
New TreeSet: [1, 2, 4, 6]

Access TreeSet Elements


To access the elements of a tree set, we can use the iterator() method. In
order to use this method, we must import java.util.Iterator package. For
example,
import java.util.TreeSet;
import java.util.Iterator;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Calling iterator() method


Iterator<Integer> iterate = numbers.iterator();
System.out.print("TreeSet using Iterator: ");
// Accessing elements
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Run Code

Output

TreeSet: [2, 5, 6]
TreeSet using Iterator: 2, 5, 6,
Remove Elements
 remove() - removes the specified element from the set
 removeAll() - removes all the elements from the set
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using the remove() method


boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);

// Using the removeAll() method


boolean value2 = numbers.removeAll(numbers);
System.out.println("Are all elements removed? " + value2);
}
}
Run Code

Output

TreeSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true

Methods for Navigation


Since the TreeSet class implements NavigableSet , it provides various
methods to navigate over the elements of the tree set.
1. first() and last() Methods
 first() - returns the first element of the set
 last() - returns the last element of the set
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using the first() method


int first = numbers.first();
System.out.println("First Number: " + first);

// Using the last() method


int last = numbers.last();
System.out.println("Last Number: " + last);
}
}
Run Code

Output

TreeSet: [2, 5, 6]
First Number: 2
Last Number: 6

2. ceiling(), floor(), higher() and lower() Methods


 higher(element) - Returns the lowest element among those elements that
are greater than the specified element .
 lower(element) - Returns the greatest element among those elements that
are less than the specified element .

 ceiling(element) - Returns the lowest element among those elements that


are greater than the specified element . If the element passed exists in a tree
set, it returns the element passed as an argument.
 floor(element) - Returns the greatest element among those elements that
are less than the specified element . If the element passed exists in a tree set,
it returns the element passed as an argument.
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using higher()
System.out.println("Using higher: " + numbers.higher(4));

// Using lower()
System.out.println("Using lower: " + numbers.lower(4));

// Using ceiling()
System.out.println("Using ceiling: " + numbers.ceiling(4));

// Using floor()
System.out.println("Using floor: " + numbers.floor(3));

}
}
Run Code

Output

TreeSet: [2, 4, 5, 6]
Using higher: 5
Using lower: 2
Using ceiling: 4
Using floor: 2

3. pollfirst() and pollLast() Methods


 pollFirst() - returns and removes the first element from the set
 pollLast() - returns and removes the last element from the set
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using pollFirst()
System.out.println("Removed First Element: " + numbers.pollFirst());

// Using pollLast()
System.out.println("Removed Last Element: " + numbers.pollLast());

System.out.println("New TreeSet: " + numbers);


}
}
Run Code

Output

TreeSet: [2, 4, 5, 6]
Removed First Element: 2
Removed Last Element: 6
New TreeSet: [4, 5]
4. headSet(), tailSet() and subSet() Methods

headSet(element, booleanValue)
The headSet() method returns all the elements of a tree set before the
specified element (which is passed as an argument).
The booleanValue parameter is optional. Its default value is false .

If true is passed as a booleanValue , the method returns all the elements


before the specified element including the specified element.
For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using headSet() with default boolean value


System.out.println("Using headSet without boolean value: " +
numbers.headSet(5));

// Using headSet() with specified boolean value


System.out.println("Using headSet with boolean value: " +
numbers.headSet(5, true));
}
}
Run Code

Output
TreeSet: [2, 4, 5, 6]
Using headSet without boolean value: [2, 4]
Using headSet with boolean value: [2, 4, 5]

tailSet(element, booleanValue)
The tailSet() method returns all the elements of a tree set after the
specified element (which is passed as a parameter) including the
specified element .

The booleanValue parameter is optional. Its default value is true .

If false is passed as a booleanValue , the method returns all the elements


after the specified element without including the specified element .

For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using tailSet() with default boolean value


System.out.println("Using tailSet without boolean value: " +
numbers.tailSet(4));

// Using tailSet() with specified boolean value


System.out.println("Using tailSet with boolean value: " +
numbers.tailSet(4, false));
}
}
Run Code
Output

TreeSet: [2, 4, 5, 6]
Using tailSet without boolean value: [4, 5, 6]
Using tailSet with boolean value: [5, 6]

subSet(e1, bv1, e2, bv2)


The subSet() method returns all the elements
between e1 and e2 including e1 .

The bv1 and bv2 are optional parameters. The default value of bv1 is true ,

and the default value of bv2 is false .

If false is passed as bv1 , the method returns all the elements


between e1 and e2 without including e1 .

If true is passed as bv2 , the method returns all the elements


between e1 and e2 , including e1 .

For example,

import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(2);
numbers.add(5);
numbers.add(4);
numbers.add(6);
System.out.println("TreeSet: " + numbers);

// Using subSet() with default boolean value


System.out.println("Using subSet without boolean value: " +
numbers.subSet(4, 6));

// Using subSet() with specified boolean value


System.out.println("Using subSet with boolean value: " +
numbers.subSet(4, false, 6, true));
}
}
Run Code

Output

TreeSet: [2, 4, 5, 6]
Using subSet without boolean value: [4, 5]
Using subSet with boolean value: [5, 6]

Set Operations
The methods of the TreeSet class can also be used to perform various set
operations.

Union of Sets
To perform the union between two sets, we use the addAll() method. For
example,
import java.util.TreeSet;;

class Main {
public static void main(String[] args) {
TreeSet<Integer> evenNumbers = new TreeSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("TreeSet1: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("TreeSet2: " + numbers);
// Union of two sets
numbers.addAll(evenNumbers);
System.out.println("Union is: " + numbers);

}
}
Run Code

Output

TreeSet1: [2, 4]
TreeSet2: [1, 2, 3]
Union is: [1, 2, 3, 4]

Intersection of Sets
To perform the intersection between two sets, we use
the retainAll() method. For example,
import java.util.TreeSet;;

class Main {
public static void main(String[] args) {
TreeSet<Integer> evenNumbers = new TreeSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("TreeSet1: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("TreeSet2: " + numbers);

// Intersection of two sets


numbers.retainAll(evenNumbers);
System.out.println("Intersection is: " + numbers);
}
}
Run Code
Output

TreeSet1: [2, 4]
TreeSet2: [1, 2, 3]
Intersection is: [2]

Difference of Sets
To calculate the difference between the two sets, we can use
the removeAll() method. For example,
import java.util.TreeSet;;

class Main {
public static void main(String[] args) {
TreeSet<Integer> evenNumbers = new TreeSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println("TreeSet1: " + evenNumbers);

TreeSet<Integer> numbers = new TreeSet<>();


numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("TreeSet2: " + numbers);

// Difference between two sets


numbers.removeAll(evenNumbers);
System.out.println("Difference is: " + numbers);
}
}
Run Code

Output

TreeSet1: [2, 4]
TreeSet2: [1, 2, 3, 4]
Difference is: [1, 3]
Subset of a Set
To check if a set is a subset of another set or not, we use
the containsAll() method. For example,
import java.util.TreeSet;

class Main {
public static void main(String[] args) {
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println("TreeSet1: " + numbers);

TreeSet<Integer> primeNumbers = new TreeSet<>();


primeNumbers.add(2);
primeNumbers.add(3);
System.out.println("TreeSet2: " + primeNumbers);

// Check if primeNumbers is subset of numbers


boolean result = numbers.containsAll(primeNumbers);
System.out.println("Is TreeSet2 subset of TreeSet1? " + result);
}
}
Run Code

Output

TreeSet1: [1, 2, 3, 4]
TreeSet2: [2, 3]
Is TreeSet2 subset of TreeSet1? True
Other Methods of TreeSet
Method Description

clone() Creates a copy of the TreeSet

contains() Searches the TreeSet for the specified element and returns a boolean result

isEmpty() Checks if the TreeSet is empty

size() Returns the size of the TreeSet

clear() Removes all the elements from the TreeSet

To learn more, visit Java TreeSet (official Java documentation).

TreeSet Vs. HashSet


Both the TreeSet as well as the HashSet implements the Set interface.
However, there exist some differences between them.
 Unlike HashSet , elements in TreeSet are stored in some order. It is
because TreeSet implements the SortedSet interface as well.
 TreeSet provides some methods for easy navigation. For
example, first() , last() , headSet( ), tailSet() , etc. It is because TreeSet also
implements the NavigableSet interface.
 HashSet is faster than the TreeSet for basic operations like add, remove,
contains and size.
TreeSet Comparator
In all the examples above, tree set elements are sorted naturally. However,
we can also customize the ordering of elements.

For this, we need to create our own comparator class based on which
elements in a tree set are sorted. For example,

import java.util.TreeSet;
import java.util.Comparator;

class Main {
public static void main(String[] args) {

// Creating a tree set with a customized comparator


TreeSet<String> animals = new TreeSet<>(new CustomComparator());

animals.add("Dog");
animals.add("Zebra");
animals.add("Cat");
animals.add("Horse");
System.out.println("TreeSet: " + animals);
}

// Creating a comparator class


public static class CustomComparator implements Comparator<String> {

@Override
public int compare(String animal1, String animal2) {
int value = animal1.compareTo(animal2);

// elements are sorted in reverse order


if (value > 0) {
return -1;
}
else if (value < 0) {
return 1;
}
else {
return 0;
}
}
}
}
Run Code

Output

TreeSet: [Zebra, Horse, Dog, Cat]

In the above example, we have created a tree set


passing CustomComparator class as an argument.
The CustomComparator class implements the Comparator interface.
We then override the compare() method. The method will now sort elements
in reverse order.
To learn more, visit Java Comparator (official Java documentation).

You might also like