Java Collections
Java Collections
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 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.(reason :
arraylist.add(index,30) before 1,2,3,4 then add(2,50) :1,2,50,3,4
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 OPERATIONS: add(element),
o add(index,element)
o addAll(Arrays.asList(specified elements))
o addAll(another ArrayList)
o remove(element)
o removeAll(Arrays.asList(particular elements))
o removeAll(another ArrayList)
o size()
o get(index)
o set(index,element)
o indexOf(element);
o sort()
Note : Iterator is used to traverse the elements in a collection like list,set, queue in ascending order
from first element to last element.
Iterator<> it = listname.iterator() for this we have to use hasNext() and next()
To traverse in a reverse order we have another techniques like
Collections.reverse(listname)
ListIterator to tranverse elements both in forward and backward directions
backward
ListIterator<String> it = list.listIterator(list.size()); for this we have to use hasPrevious() and
previous()
forward
ListIterator<String> it = list.listIterator(); for this we have to use hasNext() and next()
ListIterator<String> it = list.listIterator(position ); we can retrieve from specified postion
One of the key features of a LinkedList is its dynamic size, meaning it can grow or shrink as needed.
This is because each element is stored in its own node, allowing for efficient insertion and deletion
operations. However, accessing elements by index in a LinkedList is less efficient compared to
arrays, as it requires traversing the list from the beginning or end to reach the desired element.
The LinkedList class in Java provides various methods to manipulate the list, such as adding or
removing elements, accessing elements by index, and searching for elements. Additionally, it offers
methods to perform operations like adding elements at the beginning or end of the list, inserting
elements at specific positions, and removing elements by index or value.
Hierarchy of LinkedList Class
The List interface extends the Collection interface and represents an ordered collection of elements.
Lists allow duplicate elements and provide methods to access elements by their integer index.
The LinkedList class implements the List interface and represents a doubly linked list data structure.
A LinkedList consists of a series of nodes, where each node contains a reference to the next node and
the previous node in the sequence. It allows for efficient insertion and deletion operations, as each
node only needs to update its neighboring nodes' references. However, accessing elements by index in
a LinkedList is less efficient compared to an ArrayList, as it requires traversing the list from the
beginning or end to reach the desired element.
Doubly Linked List
In Java, a doubly linked list is a type of linked list in which each node contains a reference to the next
node and the previous node in the sequence. It allows for traversal of the list in both forward and
backward directions, making it different from a singly linked list that only allows traversal in one
direction.
One advantage of a doubly linked list is that it allows for more efficient removal of elements
compared to a singly linked list, as it is possible to directly access the previous node of a given node.
It makes it easier to remove elements from the middle of the list without having to traverse the entire
list.
In the case of a doubly linked list, we can add or remove elements from both sides.
However, one drawback of a doubly linked list is that it requires more memory compared to a singly
linked list, as each node contains an additional pointer to the previous node. Additionally, maintaining
the previous pointers adds complexity to the implementation of the list
1. LinkedList<String> ll=new LinkedList<String>();
Operations
add(element)
add(index,element)
addAll(index,Arrays.asList(elements))
addAll(another list)
addFirst(element)
addLast(element)
remove(index)-> strings,integers for all types
remove(element)
removeAll(Specified elements)
removeAll(Another list)
1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<book> list=new LinkedList<book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }
ArrayList LinkedList
1) ArrayList internally uses a dynamic array to store LinkedList internally uses a doubly linked list to
the elements. store the elements.
3) An ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data. LinkedList is better for manipulating data.
5) The memory location for the elements of an The location for the elements of a linked list is not
ArrayList is contiguous. contagious.
boolean bool = firstList.equals(secondList); //returns false because lists are not equal
In this example, we have created two ArrayList firstList and secondList of String type.
We have created a static method compareList() which parses two
ArrayList ls1 and ls2 as an argument and returns a boolean value. The method converts a
list into String. The contentEquals() method compares the String to the specified
StringBuffer.
Java List
List in Java provides the facility to maintain the ordered collection. It contains the index-based
methods to insert, update, delete and search the elements. It can have the duplicate elements also.
We can also store the null elements in the list.
The List interface is found in the java.util package and inherits the Collection interface. It is a
factory of ListIterator interface. Through the ListIterator, we can iterate the list in forward and
backward directions. The implementation classes of List interface are ArrayList, LinkedList,
Stack and Vector. The ArrayList and LinkedList are widely used in Java programming. The
Vector class is deprecated since Java 5.
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.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of
their hashcode.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.
A list can contain duplicate elements whereas Set contains unique elements only.
Add,remove
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. It
inherits the HashSet class and implements the Set interface.
o Java LinkedHashSet class provides all optional set operations and permits null elements.
Note: Keeping the insertion order in the LinkedHashset has some additional costs, both in terms
of extra memory and extra CPU cycles. Therefore, if it is not required to maintain the insertion
order, go for the lighter-weight HashMap or the HashSet instead.
The LinkedHashSet class extends the HashSet class, which implements the Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.
LinkedHashSet Class Declaration
TreeSet in Java is a collection class that implements the Set interface and stores unique elements
in a sorted order. It’s part of the Java java.util package and is commonly used when you need to
maintain a collection of sorted and unique items. Here’s a clear breakdown of TreeSet and how it
works:
1. Sorted Order: Elements in a TreeSet are automatically sorted in natural order (e.g.,
alphabetical for strings, ascending for numbers) or in a custom order defined by a
Comparator.
2. Unique Elements: Like all Set implementations, TreeSet does not allow duplicate
elements.
4. Red-Black Tree: TreeSet is backed by a Red-Black tree, a balanced binary search tree,
which ensures efficient performance for insertions, deletions, and lookups.
Performance Characteristics
Time Complexity: Operations like add, remove, and contains have a time complexity of
O(log n) because of the Red-Black tree.
1. Adding Elements: Use add(element) to add an element. If the element already exists, it
won’t be added again.
4. Getting Size: Use size() to get the number of elements in the TreeSet.
Copy code
import java.util.TreeSet;
numbers.add(10);
numbers.add(5);
numbers.add(15);
// Remove an element
numbers.remove(10);
System.out.println("Ascending Order:");
System.out.println("\nDescending Order:");
3. Custom Sorting: You can pass a custom Comparator to TreeSet if you want a specific
order.
4. Null Values: TreeSet does not allow null elements, as it cannot determine the order for
null.
Sorted Collection: When you need a sorted collection without duplicates, such as storing
unique names in alphabetical order.
Range Views: Ideal for scenarios where you need subsets within a specific range, as
TreeSet allows retrieving elements in specific ranges using methods like subSet(),
headSet(), and tailSet().
In summary, TreeSet is an efficient collection for maintaining a sorted and unique set of
elements, useful for scenarios requiring ordering and fast lookups without duplicates.
In Java, a Queue is a collection that follows the First-In-First-Out (FIFO) principle. It is part of
the java.util package and provides functionality to handle elements in a sequence where elements
are added at the end (rear) and removed from the front (head). The Queue interface in Java has
multiple implementations, with LinkedList and PriorityQueue being the most commonly used
classes.
1. FIFO Order: Items are added to the back (tail) of the queue and removed from the front
(head). This ensures that the first element added is the first one removed.
3. Types of Queues:
The Queue interface provides several methods to add, remove, and inspect elements. Here are
some commonly used methods:
1. Add Elements:
o add(E e): Adds an element to the queue. Throws an exception if the queue is full.
o offer(E e): Adds an element to the queue. Returns false if the queue is full (useful
in bounded queues).
2. Remove Elements:
o remove(): Removes and returns the head of the queue. Throws an exception if the
queue is empty.
o poll(): Removes and returns the head of the queue. Returns null if the queue is
empty.
3. Examine Elements:
o element(): Retrieves, but does not remove, the head of the queue. Throws an
exception if the queue is empty.
o peek(): Retrieves, but does not remove, the head of the queue. Returns null if the
queue is empty.
java
Copy code
import java.util.LinkedList;
import java.util.Queue;
queue.add("A");
queue.add("B");
queue.add("C");
System.out.println("Queue after removals: " + queue); // Output: Queue after removals: [C]
A PriorityQueue in Java is a special type of queue where elements are ordered based on their
priority rather than the insertion order. It is part of the java.util package and implements the
Queue interface. This makes it suitable for scenarios where the highest (or lowest) priority
element needs to be processed first.
1. Order of Elements:
o You can define a custom ordering by providing a Comparator when you create
the queue.
2. No Fixed Order for Equal Priority: Elements with the same priority may not appear in
a fixed order.
3. Does Not Allow null Values: PriorityQueue doesn’t support null elements.
In a PriorityQueue, elements with the highest priority are served first. For example, if integers are
added, the smallest integer will be dequeued first (by default). When custom priority is needed,
you can use a comparator to define specific rules for ordering.
1. Add Elements:
o add(E e): Adds an element to the queue. Throws an exception if it fails.
o offer(E e): Similar to add, but returns false if it fails instead of throwing an
exception.
2. Remove Elements:
o poll(): Removes and returns the highest-priority element or null if the queue is
empty.
3. Examine Elements:
o peek(): Retrieves, but does not remove, the highest-priority element or returns
null if the queue is empty.
Example of PriorityQueue
Here’s a simple example to demonstrate the functionality of PriorityQueue with default natural
ordering (smallest numbers first):
java
Copy code
import java.util.PriorityQueue;
pq.add(20);
pq.add(10);
pq.add(30);
// Display elements (Note: Order may vary in the output, as they are in a heap)
To reverse the natural ordering, or to apply a specific rule, you can use a custom comparator.
Here’s an example using a comparator to create a max-priority queue (highest number first):
java
Copy code
import java.util.PriorityQueue;
import java.util.Comparator;
// Create a PriorityQueue with custom comparator (largest element has highest priority)
pq.add(20);
pq.add(10);
pq.add(30);
The interface called Deque is present in java.util package. It is the subtype of the interface queue.
The Deque supports the addition as well as the removal of elements from both ends of the data
structure. Therefore, a deque can be used as a stack or a queue. We know that the stack supports
the Last In First Out (LIFO) operation, and the operation First In First Out is supported by a
queue. As a deque supports both, either of the mentioned operations can be performed on it.
Deque is an acronym for "double ended queue".
Method Description
We know that it is not possible to create an object of an interface in Java. Therefore, for
instantiation, we need a class that implements the Deque interface, and that class is ArrayDeque.
It grows and shrinks as per usage. It also inherits the AbstractCollection class.
A map contains values on the basis of key, i.e. key and value pair. Each key and value pair is
known as an entry. A Map contains unique keys.
A Map is useful if you have to search, update or delete elements on the basis of a key.
There are two interfaces for implementing Map in java: Map and SortedMap, and three classes:
HashMap, LinkedHashMap, and TreeMap. The hierarchy of Java Map is given below:
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and
LinkedHashMap allow null keys and values, but TreeMap doesn't allow any null key or value.
Advertisement
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
Class Description
The Map interface in Java represents a collection of key-value pairs where each key is unique.
It’s commonly implemented by classes such as HashMap, LinkedHashMap, and TreeMap. Here
are some useful methods provided by the Map interface to work with key-value mappings:
put(K key, V value): Adds a key-value pair to the map or updates the value if the key
already exists.
putIfAbsent(K key, V value): Adds the key-value pair only if the key is not already
present in the map.
get(Object key): Retrieves the value associated with the specified key. Returns null if the
key does not exist.
remove(Object key): Removes the key-value pair for the specified key and returns the
value, or null if the key does not exist.
replace(K key, V newValue): Replaces the value associated with the specified key if it
exists.
replace(K key, V oldValue, V newValue): Replaces the value if the key exists and is
currently mapped to the old value.
2. Bulk Operations
putAll(Map<? extends K, ? extends V> m): Copies all of the mappings from the
specified map to this map.
containsKey(Object key): Checks if the map contains a mapping for the specified key.
containsValue(Object value): Checks if the map contains one or more keys mapped to
the specified value.
entrySet(): Returns a Set view of all key-value pairs (entries) in the map, allowing easy
iteration.
Map.Entry is a nested interface within the Map interface in Java. It represents a key-value pair
(an entry) in a Map. Using Map.Entry, you can work with individual entries in the map, making it
especially useful when iterating over entries.
3. Methods in Map.Entry:
o setValue(V value): Replaces the value corresponding to this entry with the
specified value. This is useful if you want to update values directly while
iterating.
Example Usage
Here’s how to use Map.Entry with a HashMap to iterate over and manipulate the map’s entries:
java
Copy code
import java.util.HashMap;
import java.util.Map;
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
if (entry.getKey().equals("Alice")) {
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and value pair,
where keys should be unique. If you try to insert the duplicate key, it will replace the element of
the corresponding key. It is easy to perform operations using the key index like updation,
deletion, etc. HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to
store the null elements as well, but there should be only one null key. Since Java 5, it is denoted
as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class
and implements the Map interface.
Points to remember
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
What is Hashing
It is the process of converting an object into an integer value. The integer value helps in indexing
and faster searches.
What is HashMap
HashMap is a part of the Java collection framework. It uses a technique called Hashing. It
implements the map interface. It stores the data in the pair of Key and Value. HashMap contains
an array of the nodes, and the node is represented as a class. It uses an array and LinkedList data
structure internally for storing Key and Value. There are four fields in HashMap.
Points to remember
o Java LinkedHashMap may have one null key and multiple null values.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Java TreeMap class is a red-black tree based implementation. It provides an efficient means of
storing key-value pairs in sorted order.
o Java TreeMap contains values based on the key. It implements the NavigableMap
interface and extends AbstractMap class.
o Java TreeMap cannot have a null key but can have multiple null values.
Map Methods
put(key,value)
get(key)
remove(key)
clear()
replace(key , new_val);
size()
i.e getkey()
getValue()
setValue()
HashMap TreeMap
1) HashMap can contain one null key. TreeMap cannot contain any null key.
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains values based
on the key.
HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.
But there are many differences between HashMap and Hashtable classes that are given below.
;HashMap Hashtable