Unit 4
Unit 4
UNIT – IV
The Collections Framework (java.util)- Collections overview, Collection Interfaces, The Collection
classes- Array List, Linked List, Hash Set, Tree Set, Priority Queue, Array Deque. Accessing a
Collection via an Iterator, Using an Iterator, The For-Each alternative, Map Interfaces and Classes,
Comparators, Collection algorithms, Arrays, The Legacy Classes and Interfaces- Dictionary,
Hashtable ,Properties, Stack, Vector
More Utility classes, String Tokenizer, Bit Set, Date, Calendar, Random, Formatter, Scanner
A Java collection framework provides an architecture to store and manipulate a group of objects.
Interfaces
Classes
Algorithm
Interfaces:
Interface in Java refers to the abstract data types. They allow Java collections to be manipulated
independently from the details of their representation. Also, they form a hierarchy in object-oriented
programming languages.
Classes: Classes in Java are the implementation of the collection interface. It basically refers to the data
structures that are used again and again.
Algorithm: Algorithm refers to the methods which are used to perform operations such as searching and
sorting, on objects that implement collection interfaces.
The Java collection framework provides the developers to access prepackaged data structures as well as
algorithms to manipulate data.
Java Collection
Iterator interface :
It is used to traverse the list and modify the elements. Iterator interface has three methods which are
mentioned below:
public boolean hasNext() – This method returns true if the iterator has more elements.
public object next() – It returns the element and moves the cursor pointer to the next element.
public void remove() – This method removes the last elements returned by the iterator.
A List is an ordered Collection of elements which may contain duplicates. It is an interface that extends
the Collection interface.
1. ArrayList
2.LinkedList
3.Vectors
Array list:
ArrayList is the implementation of List Interface where the elements can be dynamically added or
removed from the list.
Also, the size of the list is increased dynamically if the elements are added more than the initial size.
Syntax:
Method Description
Return the index in this list of the last occurrence of the specified element, or -1 if
int lastIndexOf(Object o)
the list does not contain this element.
Object[] toArray() Returns an array containing all the elements in the list.
void trimToSize() Trims the capacity of this ArrayList instance to be the list’s current size.
Example:
import java.util.*;
class DemoArrayList{
al.add("Kmec");
al.add("501");
al.add("kmit");
al.set(1,"NGIT");
System.out.println(al.size());
System.out.println(al.indexOf("501"));
al.remove("kmit");
System.out.println(al.lastIndexOf("kmit"));
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
Linked List
Linked List: Linked List is a sequence of links which contains items. Each link contains a connection to
another link.
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List: In a singly Linked list each node in this list stores the data of
the node and a pointer or reference to the next node in the list.
list.removeFirst();
Vector:
Vectors : Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector.
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework
Syntax:
Vector object = new Vector(size,increment);
Hash Set
Hashing is the process of converting the informational content into a unique value that
is more popularly known as hash code. This hashcode is then used for indexing the
data associated with the key. The entire process of transforming the informational key
into the hashcode is performed internally.
features:
boolean isEmpty() This method returns true in case the HashSet is empty
This method returns an iterator over the elements present
Iterator iterator()
in the HashSet
This method helps in removing the specified element from
boolean remove(Object o)
the HashSet if it is present
This method returns the total number of elements present
int size()
in the HashSet
Example:
import java.util.HashSet;
import java.util.*;
System.out.println(eduCourses);
eduCourses.removeIf(str->str.contains("Java"));
System.out.println("After invoking removeIf() method: "+
eduCourses);
}
}
Tree Set:
TreeSet is similar to HashSet except that it sorts the elements in the ascending
order while HashSet doesn’t maintain any order. TreeSet allows null element but like
HashSet it doesn’t allow. Like most of the other collection classes this class is also
not synchronized.
Example:
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String args[]) {
// TreeSet of String Type
TreeSet<String> tset = new TreeSet<String>();
//Displaying TreeSet
System.out.println(tset);
Priority Queue
Java PriorityQueue class is a queue data structure implementation in which objects are processed
based on their priority. It is different from standard queues where FIFO (First-In-First-Out) algorithm is
followed.
In a priority queue, added objects are according to their priority. By default, the priority is determined
by objects’ natural ordering. Default priority can be overridden by a Comparator provided at queue
construction time.
PriorityQueue Features
PriorityQueue is an unbounded queue and grows dynamically. The default initial capacity
is '11' which can be overridden using initialCapacity parameter in appropriate constructor.
It does not allow NULL objects.
Objects added to PriorityQueue MUST be comparable.
The objects of the priority queue are ordered by default in natural order.
A Comparator can be used for custom ordering of objects in the queue.
The head of the priority queue is the least element based on the natural ordering or
comparator based ordering. When we poll the queue, it returns the head object from the
queue.
If multiple objects are present of same priority the it can poll any one of them randomly.
PriorityQueue is not thread safe. Use PriorityBlockingQueue in concurrent environment.
It provides O(log(n)) time for add and poll methods.
2. Java PriorityQueue Example
Example:
Employee.java
public class Employee implements Comparable<Employee> {
@Override
public int compareTo(Employee emp) {
return this.getId().compareTo(emp.getId());
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
}
Array Deque
Creating ArrayDeque
In order to create an array deque, we must import the java.util.ArrayDeque
package.
add() - inserts the specified element at the end of the array deque
addFirst() - inserts the specified element at the beginning of the array
deque
addLast() - inserts the specified at the end of the array deque (equivalent
to add())
Note: If the array deque is full, all these methods add(), addFirst() and
addLast() throws IllegalStateException.
Example,
import java.util.ArrayDeque;
class Main {
public static void main(String[] args) {
ArrayDeque<String> animals= new ArrayDeque<>();
// Using add()
animals.add("Dog");
// Using addFirst()
animals.addFirst("Cat");
// Using addLast()
animals.addLast("Horse");
System.out.println("ArrayDeque: " + animals);
}
}
More Methods:
offer() - inserts the specified element at the end of the array deque
offerFirst() - inserts the specified element at the beginning of the array
deque
offerLast() - inserts the specified element at the end of the array deque
remove() - returns and removes an element from the first element of the
array deque
remove(element) - returns and removes the specified element from the
head of the array deque
removeFirst() - returns and removes the first element from the array deque
(equivalent to remove())
removeLast() - returns and removes the last element from the array deque
Iterator
As shown in the Class Diagram below, Java Iterator has four methods. We are
already familiar with first four methods. Oracle Corp has added fourth method to this
interface in Java SE 8 release.
Example-1
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
// Getting Iterator
Iterator<String> namesIterator = names.iterator();
// Traversing elements
while(namesIterator.hasNext()){
System.out.println(namesIterator.next());
}
}
}
Example-2:-
import java.util.LinkedList;
import java.util.List;
}
}
Characteristics of a Map:
B ecau se a Map is n ot a tru e collection ,its ch aracteristics an d b eh aviors are d ifferen t th an th e oth er
collection s like List or Set.
A Map can n ot con tain d u p licate keys an d each key can map to at most on e valu e. S ome
imp lemen tation s allow n u ll key an d n u ll valu e (HashMap an d LinkedHashMap) b u t some d oes
n ot (TreeMap).
2. Implementations of Map
In the inheritance tree of the Map interface, there are several
implementations but only 3 major, common, and general purpose
implementations - they are HashMap and LinkedHashMap and TreeMap.
Let’s see the characteristics and behaviors of each implementation:
HashMap: this implementation uses a hash table as the underlying data
structure. It implements all of the Map operations and allows null values
and one null key. This class is roughly equivalent to Hashtable - a legacy
data structure before Java Collections Framework, but it is not
synchronized and permits nulls. HashMap does not guarantee the order of
its key-value elements. Therefore, consider to use a HashMap when order
does not matter and nulls are acceptable.
LinkedHashMap: this implementation uses a hash table and a linked list
as the underlying data structures, thus the order of a LinkedHashMap is
predictable, with insertion-order as the default order. This implementation
also allows nulls like HashMap. So consider using a LinkedHashMap
when you want a Map with its key-value pairs are sorted by their insertion
order.
TreeMap: this implementation uses a red-black tree as the underlying data
structure. A TreeMap is sorted according to the natural ordering of its
keys, or by a Comparator provided at creation time. This implementation
does not allow nulls. So consider using a TreeMap when you want a Map
sorts its key-value pairs by the natural order of the keys (e.g. alphabetic
order or numeric order), or by a custom order you specify.
So far you have understood the key differences of the 3 major Map’s
implementations. And the code examples in this tutorial are around them.
Now, let’s see how to use Map for your daily coding.
mapHttpErrors.put(200, "OK");
mapHttpErrors.put(303, "See Other");
mapHttpErrors.put(404, "Not Found");
System.out.println(mapHttpErrors);
This maps HTTP status codes to their descriptions.
Map<Integer, String> mapErrors = new HashMap<>(mapHttpErrors);
The map mapErrors is created with initial elements copied from the map
mapHttpErrors.
Creating a LinkedHashMap:
The following code creates a LinkedHashMap that maps phone numbers
with contact names:
mapContacts.put("0169238175", "Tom");
mapContacts.put("0904891321", "Peter");
mapContacts.put("0945678912", "Mary");
mapContacts.put("0981127421", "John");
System.out.println(mapContacts);
Creating a TreeMap:
The following code creates a TreeMap that maps file extensions to
programming languages:
Map<String, String> mapLang = new TreeMap<>();
mapLang.put(".c", "C");
mapLang.put(".java", "Java");
mapLang.put(".pl", "Perl");
mapLang.put(".cs", "C#");
mapLang.put(".php", "PHP");
mapLang.put(".cpp", "C++");
mapLang.put(".xml", "XML");
System.out.println(mapLang);
Output:
1
2
3
if (mapHttpErrors.containsKey("200")) {
System.out.println("Http status 200");
}
Output:
1
Found: Http status 200
if (removedValue != null) {
System.out.println("Removed value: " + removedValue);
}
value was removed. This method is useful in case we really care about the
key and value to be removed.
I recommend you to read this well-know Java collection book to learn in-
depth about Java collections framework.
1
2
3
4
5
if (mapHttpErrors.isEmpty()) {
System.out.println("No Error");
} else {
System.out.println("Have HTTP Errors");
}
Output:
1
Have HTTP Errors
mapCountryCodes.put("1", "USA");
mapCountryCodes.put("44", "United Kingdom");
mapCountryCodes.put("33", "France");
mapCountryCodes.put("81", "Japan");
while (iterator.hasNext()) {
String code = iterator.next();
String country = mapCountryCodes.get(code);
mapCountryCodes.forEach(
(code, country) -> System.out.println(code + " => " + country));
The putAll(Map<K, V> m) method copies all of the mappings from the
specified map to this map. Here’s an example:
Map<Integer, String> countryCodesEU = new HashMap<>();
countryCodesWorld.putAll(countryCodesEU);
Comparators
Java Comp arator in terface u sed to sort a array or list of ob jects b ased on cu stom ord er. Cu stom
ord erin g of elemen ts is imp osed b y imp lemen tin g Comp arator.comp are() meth od in th e ob jects.
Comparator.compare()
To enable total ordering on objects, we need to create class which implements
Comparator interface. Then we need to override it’s compare(T o1, T o2) method.
It compares its two arguments for order. It returns a negative integer, zero, or a
positive integer as the first argument is less than, equal to, or greater than the second.
The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) &&
(compare(y, z)>0)) implies compare(x, z)>0.
Example:
import java.time.LocalDate;
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", dob=" + dob + "]";
}
}
Using Comparator
import java.util.Comparator;
Comparator examples
//Order by name
Comparator.comparing(Employee::getName);
//Order by id field
Comparator.comparing(Employee::getId);
Collections.reverseOrder()
This utility method returns a comparator that imposes the reverse of the natural
ordering or total ordering on a collection of objects that implement the Comparable
interface.
Comparator.reversed();
Comparator.comparing(Employee::getName).reversed();
Collection Algorithms