Unit 4 Notes
Unit 4 Notes
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.
//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
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 contains(Object This method returns true if the passed element is present
o) within the HashSet
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;
names.add("Rams");
names.add("Posa");
names.add("Chinni");
// 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:
Because a Map is not a true collection, its characteristics and behaviors are different than the other
collections like List or Set.
A Map cannot contain duplicate keys and each key can map to at most one value. Some
implementations allow null key and null value (HashMap and LinkedHashMap) but some does
not (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
mapHttpErrors.put(200, "OK");
mapHttpErrors.put(303, "See Other");
mapHttpErrors.put(404, "Not Found");
mapHttpErrors.put(500, "Internal Server Error");
System.out.println(mapHttpErrors);
This maps HTTP status codes to their descriptions.
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
{.c=C, .cpp=C++, .cs=C#, .java=Java, .php=PHP, .pl=Perl, .xml=XML}
As you can see, the TreeMap sorts its keys by their natural ordering,
which is the alphabetical order in this case.
1
Found: Http status 200
if (removedValue != null) {
System.out.println("Removed value: " + removedValue);
}
key only if it is currently mapping to some value. This method returns the
previous value associated with the specified key.
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);
}
Set<Map.Entry<String, String>> entries = mapCountryCodes.entrySet();
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 Comparator interface used to sort a array or list of objects based on custom order. Custom
ordering of elements is imposed by implementing Comparator.compare() method in the objects.
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;
public class NameSorter implements Comparator<Employee>
{
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareToIgnoreCase( e2.getName() );
}
}
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
Algorithms:
I. Sorting Algorithm:
The sort algorithm reorders a List such that its elements are in ascending order
according to an ordering relationship. The sort operation uses a slightly optimized merge
sort algorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted
version of sets and maps, there is no sorted List collection implementation. Sorting of a
List is done with the sort( ) method.
For example, the following program prints the arguments (the arguments, given
through command line) of a List in an alphabetical order.
import java.util.*;
Searching Algorithm :
Before searching an element, the List must be sorted, Once you have sorted the
List, using Collection.sort( ) method, you can perform a quickly binary search operation
using the overridden binarySearch( ) method.
For example, the following program prints the sorted arguments list (the
arguments, given through command line) and then search the position of a specified key
value.
import java.util.*;
}
}
Dictionary:
Declaration:
public abstract class Dictionary extends Object
Constructor:
Dictionary() constructor
Syntax:
public abstract int size()
Add/ put values in dictionary
put(K key, V value) : java.util.Dictionary.put(K key, V value) adds key-value pair
to the dictionary
Syntax:
public abstract V put(K key, V value)
Syntax:
public abstract Enumeration elements()
Syntax:
Return true, if there is no key-value relation in the dictionary; else return false.
Syntax:
public abstract V remove(Object key)
Example:
import java.util.*;
public class My_Class
{
public static void main(String[] args)
{
// Initializing a Dictionary
Dictionary edu = new Hashtable();
// put() method
edu.put("1000", "Edureka");
edu.put("2000", "Platfrom");
// elements() method :
for (Enumeration i = edu.elements(); i.hasMoreElements();)
{
System.out.println("Value in Dictionary : " + i.nextElement());
}
// get() method :
System.out.println("nValue at key = 3000 : " + edu.get("2000"));
Hashtable:
This class implements a hash table, which maps keys to values. Any non-null
object can be used as a key or as a value. Hashtable is similar to HashMap except it is
synchronized. There are few more differences between HashMap and Hashtable class,
you can read them in detail at: Difference between HashMap and Hashtable.
In this tutorial we will see how to create a Hashtable, how to populate its entries
and then we will learn how to display its key-value pairs using Enumeration. At the end of
this article we will see Hashtable tutorials and methods of Hashtable class.
Example
import java.util.Hashtable;
import java.util.Enumeration;
Enumeration names;
String key;
// Creating a Hashtable
Hashtable<String, String> hashtable =
new Hashtable<String, String>();
names = hashtable.keys();
while(names.hasMoreElements()) {
key = (String) names.nextElement();
System.out.println("Key: " +key+ " & Value: " +
hashtable.get(key));
}
}
}
2) Object clone(): Creates a shallow copy of this hashtable. All the structure of
the hashtable itself is copied, but the keys and values are not cloned. This is a relatively
expensive operation.
3) boolean contains(Object value): Tests if some key maps into the specified
value in this hashtable. This operation is more expensive than the containsKey method.
Note that this method is identical in functionality to containsValue, (which is part
of the Map interface in the collections framework).
6) Object put(Object key, Object value): Maps the specified key to the specified
value in this hashtable.
7) void rehash(): Increases the size of the hash table and rehashes all of its keys.
8) Object remove(Object key): Removes the key (and its corresponding value)
from this hashtable.
11) boolean containsKey(Object key): Tests if the specified object is a key in this
hashtable.
14) Object get(Object key): Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
Properties:
The Properties class represents a persistent set of properties. The Properties can be saved to a
stream or loaded from a stream. Each key and its corresponding value in the property list is a string.
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a
Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose
keys or values are not Strings. The setProperty method should be used instead. If the store or save
method is called on a "compromised" Properties object that contains a non-String key or value, the
call will fail. Similarly, the call to the propertyNames or list method will fail if it is called on a
"compromised" Properties object that contains a non-String key.
Java properties file is used to store project configuration data or settings. In this tutorial, we will show
you how to read and write to/from a .properties file.
// print everything
prop.forEach((k, v) -> System.out.println("Key : " + k + ", Value : " + v));
String Tokenizer:
StringTokenizer class is used for creating tokens in Java. It allows an application to break or split into
small parts. Each split string part is called Token.
StringTokenizer Constructors
(String str)
str is a string to be tokenized and it considers default delimiters like newline, space, tab, carriage return
and form feed which can be further tokenized.
delim is set of delimiters that are used to tokenize the given string.
Example:
import java.util.*;
public class StringTokenizerDemo {
public static void main(String args[])
{
System.out.println("StringTokenizer Constructor 1 - ");
StringTokenizer st1 =
new StringTokenizer("Hello Readers, Welcome to DataFlair", " ");
while (st1.hasMoreTokens())
System.out.println(st1.nextToken());
System.out.println("StringTokenizer Constructor 2 - ");
StringTokenizer st2 =
new StringTokenizer("JAVA : Code : String", " :");
while (st2.hasMoreTokens())
System.out.println(st2.nextToken());
System.out.println("StringTokenizer Constructor 3 - ");
StringTokenizer st3 =
new StringTokenizer("JAVA Code String", " : ", true);
while (st3.hasMoreTokens())
System.out.println(st3.nextToken());
}
}
BitSet:
Bitsets represents fixed size sequence of N bits having values either zero or one. Zero
means value is false or unset. One means value is true or set. Bitset size is fixed at
compile time. Bitset is a class defined in java.util package. It is a special type of array
which holds bit values. It implements a vector of bits. Its size grows automatically as
more bits are needed.
This class provides us two types of constructors to form bitset from integers as well as
from strings. Those two are:
Example:
import java.util.BitSet;
public class BitSetJavaExample
{
public static void main(String args[])
{
int n=8;
BitSet p = new BitSet(n);
for(int i=0;i<n;i++)
p.set(i);
System.out.print("Bits of p are set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
BitSet q = (BitSet) p.clone();
System.out.print("nBits of q are set as : ");
for(int i=0;i<n;i++)
System.out.print(q.get(i)+" ");
for(int i=0;i<3;i++)
p.clear(i);
System.out.print("nBits of p are now set as : ");
for(int i=0;i<n;i++)
System.out.print(p.get(i)+" ");
System.out.print("nBits of p which are true : "+p);
System.out.print("The Bits of q which are true : "+q);
BitSet r= (BitSet) p.clone();
p.xor(q);
System.out.println("Output of p xor q= "+p);
p = (BitSet) r.clone();
p.and(q);
System.out.println("Output of p and q = "+p);
p = (BitSet) r.clone();
p.or(q);
System.out.println("Output of p or q = "+p);
}
}
Date:
Date class
Specify the desired pattern while creating the instance of SimpleDateFormat.
Create an object of Date class.
Call the format() method of DateFormat class and pass the date object as a parameter to
the method.
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class Example {
public static void main(String[] args) {
//"hh" in pattern is for 12 hour time format and "aa" is for AM/PM
SimpleDateFormat dateTimeInGMT = new SimpleDateFormat("yyyy-MMM-dd
hh:mm:ss aa");
//Setting the time zone
dateTimeInGMT.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateTimeInGMT.format(new Date()));
}
}
Calendar
Calendar class
Specify the desired pattern for the date and time. Similar to the step 1 of above method.
Create an object of Calendar class by calling getInstance() method of it.
Call the format() method of DateFormat and pass the Calendar.getTime() as a parameter
to the method.
DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
Calendar calobj = Calendar.getInstance();
System.out.println(df.format(calobj.getTime()));
Complete java code for getting current date and time
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
Random
Java provides the Math class in the java.util package to generate random numbers.
The Math class contains the static Math.random() method to generate random numbers
of the double type.
The random() method returns a double value with a positive sign, greater than or equal to
0.0 and less than 1.0. When you call Math.random(), under the hood, a java.util.Random
pseudorandom-number generator object is created and used.
You can use the Math.random() method with or without passing parameters. If you
provide parameters, the method produces random numbers within the given parameters.
First, multiply the magnitude of the range of values you want to cover by the result that
Math.random() produces.
Math.random() * ( max - min ) returns a value in the range [0, max – min] where max is
excluded. For example, if you want [5,10], you need to cover 5 integer values so you can
use Math.random()*5. This would return a value in the range [0,5], where 5 is not
included.
Next, shift this range up to the range that you are targeting. You do this by adding the min
value.
(Math.random() * ( max - min )) + min
To get the max value included, you need to add 1 to your range parameter (max - min).
This will return a random double within the specified range.
double x = (Math.random()*((max-min)+1))+min;
There are different ways of implementing the above expression. Let us look at a couple of
them.
You can call the preceding method from the main method by passing the arguments like
this.
Formatter
Java Formatter is a utility class that can make life simple when working with formatting stream output
in Java. It is built to operate similarly to the C/C++ printf function. It is used to format and output data
to a specific destination, such as a string or a file output stream
Formatter Construction
Example:
Regionalize Output
StringBuilder builder=new StringBuilder();
Scanner
The Scanner class of the java.util package is used to read input data from different sources like input
streams, users, files, etc.
Example:
class Main {
public static void main(String[] args) {
// Prints name
System.out.println("My name is " + name);