Collections
Collections
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
1
Advantages of the Java Collection Framework
Since the lack of a collection framework leads to, the standard methods
for grouping Java objectsusing Arrays or Vectors, or Hashtables. All of
these collections had no common interface. Therefore, though the main
aim of all the collections is the same, the implementation of all these
collections was defined independently and had no correlation among
them. And also, it is very difficult for the users to remember all the
different methods, syntax, and constructors present in every collection
class.
the following are the advantages of the collection framework.
Method Description
2
Method Description
element.
3
Method Description
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
2 public Object It returns the element and moves the cursor pointer
next() to the next element.
4
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.
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.
ArrayList
ArrayList provides us with dynamic arrays in Java. Though, it may be
slower than standard arrays but can be helpful in programs where lots of
manipulation in the array is needed. The size of an ArrayList is increased
5
automatically if the collection grows or shrinks if the objects are removed
from the collection. Java ArrayList allows us to randomly access the list.
ArrayList can not be used for primitive types, like int, char, etc. We will
need a wrapper class for such cases.
6
Constructors of ArrayList
Constructor Description
Methods of ArrayList
Method Description
7
void ensureCapacity(int When methods such as add() and addAll() are
requiredCapacity) called, if the capacity of a list is not large
enough then some extra work is done to add
enough space for the new items. It takes a bit
of time to do this, so having this happen with
every add() call is not ideal.
8
boolean remove(Object o) It is used to remove the first occurrence of
the specified element.
List<E> subList(int fromIndex, It is used to fetch all the elements that lies
int toIndex) within the given range.
ArrayList Example0
import java.util.ArrayList;
import java.util.Iterator;
9
import java.util.ListIterator;
public class ArrayListExampleOne {
ArrayList Example1
10
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListExampleOne {
11
state2.addAll(3,state);
System.out.println(state2);
System.out.println(iterator.next());
}
12
// Finding the last index of an element in a ArrayList
int index =state.indexOf("Delhi");
System.out.println("Index for element Delhi is:
"+index);
int j =state.lastIndexOf("Mumbai");
System.out.println("last index for element Mumbai is: "+j);
state.remove("MP");
System.out.println("I have removed MP");
System.out.println(state);
13
//Accessing element of the array using for each loop
for(String item:stateArray) {
System.out.println(item);
}
boolean b = state.contains("Delhi");
System.out.println("Delhi is an element of the ArrayList state:
"+b);
} }
ArrayListExample2
ArrayListExample2
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class ArrayListExampleOne {
14
arrlst1.add("E");
arrlst1.add("G");
arrlst1.add("H");
arrlst.removeAll(arrlst1);
System.out.println(arrlst);
arrlst.removeRange(0, 2);
arrlst. retainAll(arrlst1);
}
ArrayListExample3
import java.util.*;
15
Java LinkedList class
Java LinkedList class uses a doubly linked list to store the elements. It provides a
linked-list data structure. It inherits the AbstractList class and implements List
and Deque interfaces.
16
LinkedList(Collection<? It is used to construct a list containing the elements
extends E> c) of the specified collection, in the order, they are
returned by the collection's iterator.
17
Iterator<E> It is used to return an iterator over the elements
descendingIterator() in a deque in reverse sequential order.
18
E pollFirst() It retrieves and removes the first element of a list,
or returns null if a list is empty.
19
the proper sequence (from first to the last
element); the runtime type of the returned array
is that of the specified array.
However, there are many differences between the ArrayList and LinkedList
classes that are given below.
ArrayList LinkedList
5) The memory location for the The location for the elements of a
elements of an ArrayList is linked list is not contagious.
contiguous.
20
7) To be precise, an ArrayList is a LinkedList implements the doubly
resizable array. linked list of the list interface.
Points to Remember
The following are some important points to remember regarding an
ArrayList and LinkedList.
o When the rate of addition or removal rate is more than the read
scenarios, then go for the LinkedList. On the other hand, when the
frequency of the read scenarios is more than the addition or removal
rate, then ArrayList takes precedence over LinkedList.
o Since the elements of an ArrayList are stored more compact as
compared to a LinkedList; therefore, the ArrayList is more cache-
friendly as compared to the LinkedList. Thus, chances for the cache
miss are less in an ArrayList as compared to a LinkedList. Generally,
it is considered that a LinkedList is poor in cache-locality.
o Memory overhead in the LinkedList is more as compared to the
ArrayList. It is because, in a LinkedList, we have two extra links (next
and previous) as it is required to store the address of the previous
and the next nodes, and these links consume extra space. Such links
are not present in an ArrayList.
21
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.
22
Constructors of Java HashSet class
SN Constructor Description
23
ct o) from this set if it is present.
24
Java LinkedHashSet Class
Java LinkedHashSet class is a Hashtable and Linked list implementation of
the Set interface. It inherits the HashSet class and implements the Set
interface.
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.
Null elements It allows only one null It also allows only one null
element. element.
25
than LinkedHashSet
Initial Capacity 16 16
26
Java TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It
inherits AbstractSet class and implements the NavigableSet interface. The
objects of the TreeSet class are stored in ascending order.
The important points about the Java TreeSet class are:
PriorityQueue in Java
A PriorityQueue is used when the objects are supposed to be processed
based on the priority. It is known that a Queue follows the First-In-First-Out
algorithm, but sometimes the elements of the queue are needed to be
processed according to the priority, that’s when the PriorityQueue comes
into play.
27
A few important points on Priority Queue are as follows:
PriorityQueue doesn’t permit null.
We can’t create a PriorityQueue of Objects that are non-comparable
PriorityQueue are unbound queues.
The head of this queue is the least element with respect to the
specified ordering. If multiple elements are tied for the least value, the
head is one of those elements — ties are broken arbitrarily.
The queue retrieval operations poll, remove, peek,
and element access the element at the head of the queue.
It provides O(log(n)) time for add and poll methods.
Constructors:
1. PriorityQueue(): Creates a PriorityQueue with the default initial
capacity (11) that orders its elements according to their natural ordering.
PriorityQueue<E> pq = new PriorityQueue<E>();
2. PriorityQueue(Collection<E> c): Creates a PriorityQueue
containing the elements in the specified collection.
PriorityQueue<E> pq = new PriorityQueue<E>(Collection<E> c);
3. PriorityQueue(int initialCapacity): Creates a PriorityQueue with the
specified initial capacity that orders its elements according to their
natural ordering.
PriorityQueue<E> pq = new PriorityQueue<E>(int initialCapacity);
4. PriorityQueue(int initialCapacity, Comparator<E>
comparator): Creates a PriorityQueue with the specified initial capacity
that orders its elements according to the specified comparator.
PriorityQueue<E> pq = new PriorityQueue(int initialCapacity,
Comparator<E> comparator);
5. PriorityQueue(PriorityQueue<E> c): Creates a PriorityQueue
containing the elements in the specified priority queue.
PriorityQueue<E> pq = new PriorityQueue(PriorityQueue<E> c);
METHOD DESCRIPTION
28
METHOD DESCRIPTION
29
jobs like critical system updates may be scheduled ahead of lower-
priority jobs like data backups.
Online Marketplaces: In online marketplaces, priority queues can be
used to manage the delivery of products to customers. High-priority
orders like express shipping may be given priority over standard
shipping orders.
30
Map Interface in Java
In Java, Map Interface is present in java.util package represents a
mapping between a key and a value. Java Map interface is not a subtype
of the Collection interface. Therefore it behaves a bit differently from the
rest of the collection types. A map contains unique keys. 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.
Maps are perfect to use for key-value association mapping such as
dictionaries. The maps are used to perform lookups by keys or when
someone wants to retrieve and update elements by keys. Some common
scenarios are as follows:
A map of error codes and their descriptions.
A map of zip codes and cities.
A map of managers and employees. Each manager (key) is associated
with a list of employees (value) he manages.
A map of classes and students. Each class (key) is associated with a
list of students (value).
1. A Map cannot contain duplicate keys and each key can map to at most
one value. Some implementations allow null key and null values like
the HashMap and LinkedHashMap, but some do not like the TreeMap.
31
2. The order of a map depends on the specific implementations. For
example, TreeMap and LinkedHashMap have predictable orders,
while HashMap does not.
3. There are two interfaces for implementing Map in Java. They are Map
and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.
32
Method Action Performed
33
HashMap in Java
HashMap provides the basic implementation of the Map interface of
Java. HashMap in Java stores the data in (Key, Value) pairs, and you can
access them by an index of another type (e.g. an Integer). One object is
used as a key (index) to another object (value). If you try to insert the
duplicate key in HashMap, it will replace the element of the
corresponding key.
34
35
Java LinkedHashMap class
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map
interface, with predictable iteration order. It inherits HashMap class and
implements the Map interface.
Points to remember
o Java LinkedHashMap contains values based on the key.
o Java LinkedHashMap contains unique elements.
o Java LinkedHashMap may have one null key and multiple null values.
o Java LinkedHashMap is non synchronized.
o Java LinkedHashMap maintains insertion order. To maintain the order of
elements, the linked hashmap modifies the Map.Entry class of HashMap by
adding pointers to the next and previous entries:
o The initial default capacity of Java HashMap class is 16 with a load factor of
0.75
36
Java TreeMap class
37
Java Hashtable class
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.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas
loadFactor is 0.75.
38
Java Vector
The Vector class implements a growable array of objects.
Vectors fall in legacy classes, but now it is fully compatible with
collections.
It is found in java.util package and implement the List interface, so we
can use all the methods of the List interface.
Vector implements a dynamic array which means it can grow or shrink
as required. Like an array, it contains components that can be
accessed using an integer index.
They are very similar to ArrayList, but Vector is synchronized and has
some legacy methods that the collection framework does not contain.
It also maintains an insertion order like an ArrayList. Still, it is rarely
used in a non-thread environment as it is synchronized, and due to
this, it gives a poor performance in adding, searching, deleting, and
updating its elements.
The Iterators returned by the Vector class are fail-fast. In the case of
concurrent modification, it fails and throws
the ConcurrentModificationException.
39
Java Stack
The stack is a linear data structure that is used to store the collection of
objects.
It is based on Last-In-First-Out (LIFO).
Stack is a class that falls under the Collection framework that extends
the Vector class.
It also implements interfaces List, Collection, Iterable, Cloneable,
Serializable. It represents the LIFO stack of objects.
40
value of that function.
41
Java Comparable interface
Java Comparable interface is used to order the objects of the user-defined
class. This interface is found in java.lang package and contains only one
method named compareTo(Object). It provides a single sorting sequence only,
i.e., you can sort the elements on the basis of single data member only. For
example, it may be rollno, name, age or anything else.
It provides multiple sorting sequences, i.e., you can sort the elements on
the basis of any data member, for example, rollno, name, age or anything
else.
42
Properties class can specify other properties list as it’s the default. If a
particular key property is not present in the original Properties list, the
default properties will be searched.
Properties object does not require external synchronization and
Multiple threads can share a single Properties object.
Also, it can be used to retrieve the properties of the system.
43