Java Unit 4 Part A Notes
Java Unit 4 Part A Notes
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).
1. Iterator<T> iterator()
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.
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.
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.
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:
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
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:
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
import java.util.*;
class ArrayList8 {
Output:
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:
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:
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:
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.
Creating a Vector
Here is how we can create vectors in Java.
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:
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<>();
// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");
animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}
Output
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
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");
// 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
contains() searches the vector for specified element and returns a boolean result
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<>();
Output
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
Output
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<>();
}
}
Run Code
Output
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<>();
// Search an element
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
}
}
Output
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<>();
Output
Methods of Queue
The Queue interface includes all the methods of the Collection interface. It is
because Collection is the super interface of Queue .
class Main {
Output
Queue: [1, 2, 3]
Accessed Element: 1
Removed Element: 1
Updated Queue: [2, 3]
class Main {
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.
Methods of PriorityQueue
The PriorityQueue class provides the implementation of all the methods
present in the Queue interface.
For example,
import java.util.PriorityQueue;
class Main {
public static void main(String[] args) {
// Creating a priority queue
PriorityQueue<Integer> numbers = new PriorityQueue<>();
Output
PriorityQueue: [2, 4]
Updated PriorityQueue: [1, 4, 2]
class Main {
public static void main(String[] args) {
Output
PriorityQueue: [1, 4, 2]
Accessed Element: 1
import java.util.PriorityQueue;
class Main {
public static void main(String[] args) {
Output
PriorityQueue: [1, 4, 2]
Is the element 2 removed? true
Removed Element Using poll(): 1
class Main {
public static void main(String[] args) {
Output
Searches the priority queue for the specified element. If the element is found, it returns
contains(element)
true , if not it returns false .
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);
}
}
@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]
class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
Output
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.
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
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<>();
Output
animals.add(1, "Horse");
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
Output
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.
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);
Output
languages.set(3, "Kotlin");
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
Output
Here, the remove() method takes the index number as the parameter. And,
removes the element specified by the index number.
Other Methods
Methods Description
addFirst() adds the specified element at the beginning of the linked list
addLast() adds the specified element at the end 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);
Output
class Main {
public static void main(String[] args){
Deque<String> animals = new LinkedList<>();
animals.addFirst("Dog");
System.out.println("LinkedList after addFirst(): " + animals);
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);
Output
Whenever an element is added, prev and next Whenever an element is added, all elements
address are changed. after that position are shifted.
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.
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.
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.
class Main {
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).
class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
Output
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).
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.
Change elements
Remove elements
class Main {
public static void main(String[] args){
// create linkedlist
LinkedList<String> animals = new LinkedList<>();
Output
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
Output
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.
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
Output
languages.set(3, "Kotlin");
Here, the set() method changes the element at index 3 to Kotlin .
class Main {
public static void main(String[] args) {
LinkedList<String> languages = new LinkedList<>();
Output
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
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
poll() returns and removes the first element from the linked list
offer() adds the specified element at the end of the linked list
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);
Output
class Main {
public static void main(String[] args){
Deque<String> animals = new LinkedList<>();
animals.addFirst("Dog");
System.out.println("LinkedList after addFirst(): " + animals);
Output
LinkedList: [Cow]
LinkedList after addFirst(): [Dog, Cow]
LinkedList after addLast(): [Dog, Cow, Zebra]
LinkedList after removeFirst(): [Cow, Zebra]
LinkedList after removeLast(): [Cow]
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);
Output
LinkedList: [Cow, Cat, Dog]
Accessing linked list elements:
Cow, Cat, Dog,
Whenever an element is added, prev and next address Whenever an element is added, all elements after th
are changed. position are shifted.
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)
class Main {
// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);
Output
Set1: [2, 3]
Set2: [1, 2]
Union is: [1, 2, 3]
class Main {
}
}
Run Code
Output
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.
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,
By default,
Methods of HashSet
The HashSet class provides various methods that allow us to perform
various operations on the set.
import java.util.HashSet;
class Main {
public static void main(String[] args) {
HashSet<Integer> evenNumber = new HashSet<>();
Output
HashSet: [2, 4, 6]
New HashSet: [2, 4, 5, 6]
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);
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);
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);
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);
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);
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);
Output
HashSet1: [1, 2, 3, 4]
HashSet2: [2, 3]
Is HashSet2 is a subset of HashSet1? true
contains() Searches the HashSet for the specified element and returns a boolean result
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.
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.
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,
By default,
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);
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.
import java.util.LinkedHashSet;
class Main {
public static void main(String[] args) {
LinkedHashSet<Integer> evenNumber = new LinkedHashSet<>();
Output
LinkedHashSet: [2, 4, 6]
New LinkedHashSet: [2, 4, 6, 5]
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();
// 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
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);
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);
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);
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);
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);
Output
LinkedHashSet1: [1, 2, 3, 4]
LinkedHashSet2: [2, 3]
Is LinkedHashSet2 is a subset of LinkedHashSet1? true
Other Methods Of LinkedHashSet
Method Description
contains() Searches the LinkedHashSet for the specified element and returns a boolean result
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 .
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
class Main {
// 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
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.
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.
import java.util.TreeSet;
class Main {
public static void main(String[] args) {
Output
TreeSet: [2, 4, 6]
New TreeSet: [1, 2, 4, 6]
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);
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);
Output
TreeSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true
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);
Output
TreeSet: [2, 5, 6]
First Number: 2
Last Number: 6
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
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());
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 .
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);
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 .
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);
TreeSet: [2, 4, 5, 6]
Using tailSet without boolean value: [4, 5, 6]
Using tailSet with boolean value: [5, 6]
The bv1 and bv2 are optional parameters. The default value of bv1 is true ,
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);
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);
}
}
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);
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);
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);
Output
TreeSet1: [1, 2, 3, 4]
TreeSet2: [2, 3]
Is TreeSet2 subset of TreeSet1? True
Other Methods of TreeSet
Method Description
contains() Searches the TreeSet for the specified element and returns a boolean result
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) {
animals.add("Dog");
animals.add("Zebra");
animals.add("Cat");
animals.add("Horse");
System.out.println("TreeSet: " + animals);
}
@Override
public int compare(String animal1, String animal2) {
int value = animal1.compareTo(animal2);
Output