0% found this document useful (0 votes)
34 views60 pages

Unit 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views60 pages

Unit 4

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 60

Collections

The Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.
All the operations that you perform on data such as searching, sorting,
insertion, manipulation, deletion, etc. can be achieved by Java Collections.
Java Collection means a single unit of objects. The Java Collection
framework provides many interfaces (Set, List, Queue, Deque, etc.) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet, etc.).
Java Collections Framework consists of following parts:
A collections framework is a unified architecture for representing and
manipulating collections. All collections frameworks contain the following −
● Interfaces − These are abstract data types that represent collections.
Interfaces allow collections to be manipulated independently of the
details of their representation. In object-oriented languages, interfaces
generally form a hierarchy.
● Implementations, i.e., Classes − These are the concrete
implementations of the collection interfaces. In essence, they are
reusable data structures.
● Algorithms − These are the methods that perform useful computations,
such as searching and sorting, on objects that implement collection
interfaces. The algorithms are said to be polymorphic: that is, the same
method can be used on many different implementations of the
appropriate collection interface.
Another item closely associated with the Collections Framework is the Iterator
interface.
⮚ An iterator offers a general-purpose, standardized way of accessing the
elements within a collection, one at a time.
⮚ Thus, an iterator provides a means of enumerating the contents of a
collection. Because each collection implements Iterator, the elements of
any collection class can be accessed through the methods defined by
Iterator.
In addition to collections, the framework defines several map interfaces and
classes.
⮚ Maps store key/value pairs. Although maps are not collections in the
proper use of the term, they are fully integrated with collections.
Benefits of Java Collections Framework:
Java Collections framework have following benefits:
● Reduced Development Effort – It comes with almost all common types
of collections and useful methods to iterate and manipulate the data. So
we can concentrate more on business logic rather than designing our
collection APIs.
● Increased Quality – Using core collection classes that are well tested
increases our program quality rather than using any home developed
data structure.
● Reusability and Interoperability
● Reduce effort – to learn any new API if we use core collection API
classes.
The Collection Interfaces
The Collections Framework defines several interfaces.
Sr.No. Interface & Description
1 The Collection Interface This enables you to work with groups of objects;
it is at the top of the collections hierarchy.
2 The List Interface This extends Collection and an instance of List stores
an ordered collection of elements.
3 The Set This extends Collection to handle sets, which must contain
unique elements.
4 The SortedSet This extends Set to handle sorted sets.
5 The Map This maps unique keys to values.
6 The Map.Entry This describes an element (a key/value pair) in a map.
This is an inner class of Map.
7 The SortedMap This extends the Map so that the keys are maintained in
an ascending order.
The Enumeration This interface defines the methods by which you can
8 enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superseded by Iterator.
In addition to the collection interfaces, collections also use the Comparator,
RandomAccess, Iterator, and ListIterator interfaces,
● Comparator defines how two objects are compared;
● Iterator and ListIterator enumerate the objects within a collection.
● By implementing RandomAccess, a list indicates that it supports
efficient, random access to its elements.
Collection:
Collection is a generic interface that has this declaration:
interface Collection<E>
Here, E specifies the type of objects that the collection will hold.
⮚ Collection extends the Iterable interface. This means that all collections
can be cycled through by use of the for-each style for loop.
(Recall that only classes that implement Iterable can be cycled through
by the for.)
⮚ A ClassCastException is generated when one object is incompatible with
another, such as when an attempt is made to add an incompatible object
to a collection.
⮚ A NullPointerException is thrown if an attempt is made to store a null
object and null elements are not allowed in the collection.
⮚ An IllegalArgumentException is thrown if an invalid
argument is used. An IllegalStateException is thrown if an attempt is
made to add an element to a fixed-length collection that is full.

Collection Framework Specific Methods:


(We can use the following specific Methods in every Collection Framework
Classes)
🡺 add()→ Objects are added to a collection by calling add( )
🡺 remove()→ remove an element from the collection
🡺 Size()→ The number of elements currently held in a collection can be
determined
🡺 isEmpty()→ we can determine when a collection is empty
🡺 contains()→ to check whether a given object is in the collection,
we can determine whether a collection contains a specific
object by calling contains( ),
🡺 iterator()→ to provide an iterator over the collection.
Collection interface also provides bulk operations methods
that work on the entire collection.
🡺 containsAll()-To determine whether one collection contains all the
members of another
🡺 addAll()- We can add the entire contents of one collection to another by
calling addAll( ).
🡺 removeAll() - To remove a group of objects
🡺 retainAll() - can remove all elements except those of a specified group by
calling
🡺 clear( ) - To empty a collection
🡺 toArray()- provided as a bridge between collections and older APIs that
expect arrays on input.The toArray( ) methods return an array that
contains the elements stored in the invoking collection. The first returns
an array of Objects. The second returns an array of elements that have
the same type as the array specified as a parameter.
Example:
public class CollectionEx {
public static void main(String args[])
{
int i[]=new int[]{0,0,2,3,1,5,4};
Collection c=new ArrayList();
//al.add(6);
for(int j=0;j<i.length;j++)
{
c.add(i[j]);
}
System.out.println(c);
}
}
Output:
[0, 0, 2, 3, 1, 5, 4] //Collection of objects will display in Square Brackets
only([ ])
Iterator Interface Enumerates the Collection Objects
0
0
2
3
1
5
4
List Interface:
List is an ordered collection and can contain duplicate elements. You can
access any element from its index. List is more like an array with dynamic
length. List is one of the most used Collection types. ArrayList , LinkedList
Vector and Stack are implementation classes of List interface.
List interface provides useful methods to add an element at specific
index, remove/replace element based on index and to get a sub-list using
index. List is a generic interface that has this declaration:
interface List<E>
Here, E specifies the type of objects that the list will hold
ArrayList Class:
● ArrayList Class is the resizable-array implementation of the List
interface.
● Implements all optional list operations, and permits all elements,
including null.
● The ArrayList class is non synchronized.
● ArrayList Class contains Duplicate Values.
● ArrayList Class Insertion Order is Allowed
● Heterogeneous Objects are allowed (Except in TreeSet class and
TreeMap Every where Heterogeneous Objects are allowed)
Constructors:
⮚ ArraList al= new ArrayList() //default Constructor
Creates an empty Array List Object with initial Capacity 10.
Once ArrayList reaches its map capacity a new ArrayList will be created
with new Capacity=(CurrentCapacity * 3/2)+1.
⮚ ArraList al= new ArrayList(int InitialCapacity)
For example:
ArraList al= new ArrayList(1000) //we create capacity at beginning
of the Constructor
With required Capacity we can use This Constructor for not wasting the
capacity
⮚ ArrayList al=new ArrayList(Collection c)//this can implement in
every Collection Class
To Create an Equivalent ArrayList with TreeSet Collection/LinkedList
Collection/HashSet Collection….etc.
ArrayList Specific Methods:
Method Description
void add(int index, Object It is used to insert the specified element at the
element) specified position index in a list.
It is used to append all of the elements in the
boolean addAll(Collection specified collection to the end of this list, in the
c) order that they are returned by the specified
collection's iterator.
void clear() It is used to remove all of the elements from this list.
It is used to return the index in this list of the last
int lastIndexOf(Object o) occurrence of the specified element, or -1 if the list
does not contain this element.
Object[] toArray() It is used to return an array containing all of the
elements in this list in the correct order.
Object[] toArray(Object[] a) Itelements
is used to return an array containing all of the
in this list in the correct order.
boolean add(Object o) It is used to append the specified element to the end
of a list.
boolean addAll(int index, Itcollection
is used to insert all of the elements in the specified
into this list, starting at the specified
Collection c) position.
Object clone() It is used to return a shallow copy of an ArrayList.
It is used to return the index in this list of the first
int indexOf(Object o) occurrence of the specified element, or -1 if the List
does not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList
instance to be the list's current size.
Example 1: import java.util.*;
import java.util.*; public class ArrayListEx {
public class listexample{ public static void main(String[] args)
public static void main(String args[]){ {
ArrayList<String> al=new ArrayList a1=new ArrayList();
ArrayList<String>(); a1.add("M");
al.add("Amit"); a1.add("R");
al.add("Vijay"); a1.add("C");
al.add("Kumar"); a1.add("E");
al.add(0,"Kumar"); a1.add("W");
al.add(3,"Sachin"); a1.add("M");
System.out.println("Element at 2nd a1.add("W");
position: "+al.get(2)); System.out.println("In Array: "+a1);
/*for(String s:al){ System.out.println("Size of an Array:
System.out.println(s); "+a1.size());
} */
Iterator itr=al.iterator(); ArrayList a2=new ArrayList();
a2.add("M");
while(itr.hasNext()){ a2.add("R");
System.out.println(itr.next()); a2.add("C");
} a2.add("E");
} a2.add("W");
} System.out.println("In Array: "+a2);
Output: System.out.println("Size of an Array:
Element at 2nd position: Vijay "+a2.size());
Kumar a2.addAll(0,a1);
Amit System.out.println("After
Vijay Collecting"+a2);
Sachin System.out.println("Size of an Array:
Kumar "+a2.size());
if (a2.contains("M"))
{
for(int i=0;i<=a2.size();i++)
{
a2.remove("M");
}
}
System.out.println("After Removing M
from Collecting"+a2);
System.out.println("Getting the Index
Added "+a2.get(0));
System.out.println("w is at First
Occurence of a2
List:"+a2.indexOf("w"));
//Setting of all a1 to a2
a2.set(0,a1);
System.out.println("After setting
Collecting 2 List"+a2);
System.out.println("After Collecting
sublist"+a2.subList(0,2));
System.out.println("The Final List of
a2 ArrayList"+a2);
}
}
Output:
In Array: [M, R, C, E, W, M, W]
Size of an Array: 7
In Array: [M, R, C, E, W]
Size of an Array: 5
After Collecting [M, R, C, E, W, M, W,
M, R, C, E, W]
Size of an Array: 12
After Removing M Collecting [R, C, E,
W, W, R, C, E, W]
Getting the Index Added R
w is at First Occurence of a2 List:-1
After setting Collecting 2 List [[M, R, C,
E, W, M, W], C, E, W, W, R, C, E, W]
After Collecting sublist [[M, R, C, E, W,
M, W], C]
The Final List of a2 ArrayList [[M, R,
C, E, W, M, W], C, E, W, W, R, C, E, W]

LinkedList Class:
The Java LinkedList class uses doubly linked lists (we can add or remove
elements from both sides) to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque
interfaces.
The important points about Java LinkedList are:
● Java LinkedList class can contain duplicate elements.
● Java LinkedList class maintains insertion order.
● Java LinkedList class is non synchronized.
● In Java LinkedList class, manipulation is fast because no shifting needs
to occur.
● The Java LinkedList class can be used as a list, stack or queue.
All of the operations perform as could be expected for a doubly-linked
list. Operations that index into the list will traverse the list from the beginning
or the end, whichever is closer to the specified index.
In case of doubly linked lists, we can add or remove elements from both
side.
LinkedList implements the Deque interface, you have access to the methods
defined by Deque.
● To add elements to the start of a list you can use addFirst( ) or
offerFirst( ) for the Deque process.
● To add elements to the end of the list, use addLast( ) or offerLast( ) for
the Deque process.
● To obtain the first element, you can use getFirst( ) or peekFirst( ) for the
Deque process.
● To obtain the last element,use getLast( ) or peekLast( ) for the Deque
process.
● To remove the first element, use removeFirst( ) or pollFirst( ) for the
Deque process.
● To remove the last element, use removeLast( ) or pollLast( ) for Deque
process
Constructors:
LinkedList() It is used to construct an empty list.
LinkedList(Collection It is used to construct a list containing the elements of
c) the specified collection, in the order they are returned by
the collection's iterator.
Example:
import java.util.*;
class LinkedList1
{
public static void main(String[] args)
{
LinkedList a1=new LinkedList();
LinkedList a2=new LinkedList();
a1.add("M");
a1.add("R");
a1.add("C");
a1.add("E");
a1.add("W");
a1.add("M");
System.out.println("In Array: "+a1);
a1.addFirst("CAMPUS3");
a1.addLast("MAISAMMAGUDA");
System.out.println("After Adding Last: "+a1);
System.out.println("Size of an Array: "+a1.size());
//Converting collections into array
Object a[]=a1.toArray();
String str="";
for(int i=0;i<a.length;i++)
//converting array of elements into String
str+=a[i];
System.out.println("After Conversion of Collection into Array:-
"+str);
System.out.println("In Array: "+a1);
Object obj=a1.get(0);
System.out.println(""+a1.set(0,obj.toString()+"Changed to 9"));
System.out.println("After setting in a1 List: "+a1);
//Removing first and last Elements
a1.removeFirst();
a1.removeLast();
a1.removeLast();
System.out.println("Final List of a1 "+a1);
}
}
Output:
In Array: [M, R, C, E, W, M]
After Adding Last: [CAMPUS3, M, R, C, E, W, M, MAISAMMAGUDA]
Size of an Array: 8
After Conversion of Collection into Array:-
CAMPUS3MRCEWMMAISAMMAGUDA
In Array: [CAMPUS3, M, R, C, E, W, M, MAISAMMAGUDA]
CAMPUS3
After setting in a1 List: [CAMPUS3Changed to 9, M, R, C, E, W, M,
MAISAMMAGUDA]
Final List of a1 [M, R, C, E, W]
The Legacy Classes and Interfaces
● Vector class
● Stack class
Vector:
● Vector Class is the resizable-array implementation of the List interface.
● Implements all optional list operations, and permits all elements,
including null.
● The ArrayList class is synchronized (Hence the vector Objects are Thread
safe).
● Vector Class contains Duplicate Values.
● Vector Class Insertion Order is Allowed
● Heterogeneous Objects are allowed (Except in TreeSet class and
TreeMap Every where Heterogeneous Objects are allowed)

Constructors:
SN Constructor Description
1) vector() It constructs an empty vector with the default
size as 10.
It constructs an empty vector with the
2) vector(int initialCapacity) specified initial capacity and with its capacity
increment equal to zero.
3) vector(int initialCapacity, int Itspecified
constructs an empty vector with the
initial capacity and capacity
capacityIncrement) increment.
4) Vector(
E> c)
Collection<? extends It constructs a vector that contains the
elements of a collection c.
vector class methods:
Method Description
addElement() It is used to append the specified component to the end of
this vector. It increases the vector size by one.
capacity() It is used to get the current capacity of this vector.
elementAt() It is used to get the component at the specified index.
elements() It returns an enumeration of the components of a vector.
firstElement() It is used to get the first component of the vector.
insertElementAt() It is used to insert the specified object as a component in
the given vector at the specified index.
isEmpty() It is used to check if this vector has no components.
iterator() It is used to get an iterator over the elements in the list in
proper sequence.
lastElement() It is used to get the last component of the vector.
It is used to get the index of the last occurrence of the
lastIndexOf() specified element in the vector. It returns -1 if the vector
does not contain the element.
removeAllElements() Ittheissize
used to remove all elements from the vector and set
of the vector to zero.
removeElement() Ittheisargument
used to remove the first (lowest-indexed) occurrence of
from the vector.
removeElementAt() It is used to delete the component at the specified index.
replaceAll() It is used to replace each element of the list with the result
of applying the operator to that element.
retainAll() It is used to retain only that element in the vector which is
contained in the specified collection.
setElementAt() It is used to set the component at the specified index of the
vector to the specified object.
Example:
import java.util.*;
class VectorEx
{
public static void main(String args[])
{
Vector v=new Vector(); // Default initial capacity is 10.
to initialize the particular buckets
for particular elements capacity there we can
use this constructor as
Vector v =new Vector(10,1);
System.out.println(“Default element Vector Capacity:”+v.capacity());
for(int i=1;i<=10;i++)
{
v.addElement(i);
}
System.out.println(“Initial element Vector Capacity:”+v.capacity());
v.addElement(“A”);
System.out.println(“after adding element Vector Capacity:”v.capacity());
//here the Capacity is increased by initialcapacity* 2
System.out.println(“final Elements in vector:”+v);
}
}
OUTPUT:
Default element Vector Capacity:10
Initial element Vector Capacity:10
after adding element Vector Capacity:20
[1,2,3,4,5,6,7,8,9,10,A]
STACK:
It is a child class of Vector.
Stack is a specially designed class for LAST IN FIRST OUT order(LIFO).
Stack only defines the default constructor, which creates an empty stack
Constructor:
Stack s=new Stack();
Methods:
Method & Description
boolean empty()
Tests if this stack is empty. Returns true if the stack is empty, and returns false
if the stack contains elements.
Object peek( )
Returns the element on the top of the stack, but does not remove it.
Object pop( )
Returns the element on the top of the stack, removing it in the process.
Object push(Object element)
Pushes the element onto the stack. Element is also returned.
int search(Object element)
Searches for elements in the stack. If found, its offset from the top of the stack
is returned. Otherwise, -1 is returned.
Example:
import java.util.*;
class VectorEx
{
public static void main(String args[])
{
Stack s=new Stack();
s.push(“A”);
s.push(“B”);
s.push(“F”);
s.push(“J”);
System.out.println(s);
System.out.println(s.search(“A”));
System.out.println(s.search(“Z”));
}
}
OUTPUT:
[A,B,F,J]
4 //HERE the output will be as an offset of the stack.
-1 // if search element not there then the output
will be as offset of the stack is -1.

Set Interface:
Set is a collection that cannot contain duplicate elements. This interface
models the mathematical set abstraction and is used to represent sets, such as
the deck of cards.
The Java platform contains three general-purpose Set implementations:
HashSet, TreeSet, and LinkedHashSet. Set interface doesn’t allow
random-access to an element in the Collection. You can use an iterator or
foreach loop to traverse the elements of a Set.
Set is a generic interface that has this declaration:
interface Set<E>
Here, E specifies the type of objects that the set will hold.
SortedSet Interface
SortedSet is a Set that maintains its elements in ascending order. Several
additional operations are provided to take advantage of the ordering. Sorted
sets are used for naturally ordered sets, such as word lists and membership
rolls.
SortedSet is a generic interface that has this declaration:
interface SortedSet<E>.
Here, E specifies the type of objects that the set will hold.
HashSet class

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.
The important points about Java HashSet class are:
● HashSet stores the elements by using a mechanism called hashing.
● HashSet contains unique elements only.
In hashing, the informational content of a key is used to determine a unique
value, called its hash code. The hash code is then used as the index at which
the data associated with the key is stored. The transformation of the key into
its hash code is performed automatically—you never see the hash code itself.
Also, your code can’t directly index the hash table. The Advantage of hashing is
that it allows the execution time of add( ), contains( ), remove( ), and size( ) to
remain constant even for large sets.
The following constructors are defined:
Constructor Description
It is used to construct a default HashSet. (default
HashSet() capacity is 16 elements)
It is used to initialize the capacity of the hash set to
HashSet(int capacity) the given integer value capacity. The capacity grows
automatically as elements are added to the HashSet.
It is used to initialize the capacity of the hash set to
HashSet(int capacity, the given integer value capacity and the specified load
float loadFactor) factor. (default load factor or fillRatio is 0.75 )

HashSet(Collection c) It is used to initialize the hash set by using the


elements of the collection c.

Methods of Java HashSet class


Modifier & Method Description
Type
boolean add(Object o) It is used to add the specified element to this set
if it is not already present.
void clear() It is used to remove all of the elements from this
set.
boolean contains(Object o) Itspecified
is used to return true if this set contains the
element.
boolean isEmpty() It is used to return true if this set contains no
elements.
Iterator<E> iterator() It is used to return an iterator over the elements
in this set.
boolean remove(Object o) Itthisis used to remove the specified element from
set if it is present.
int size() It is used to return the number of elements in
this set.
Example1:
import java.util.*;
class hashset{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet set=new HashSet();
set.add(101);
set.add('e');
set.add(1.5);
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
set.remove("Vijay");
System.out.println("HashSet collection contains
set.contains('e'):"+set.contains('e'));
System.out.println("Size of HashSet Collection"+set.size());
//set.clear();//Traversing elements
Iterator itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
HashSet collection contains set.contains('e'): true
Size of HashSet Collection: 5
Ravi
101
e
1.5
Ajay

The LinkedHashSet Class


Java LinkedHashSet class is a Hash table and Linked list implementation of
the set interface. It inherits HashSet class and implements Set interface.
The important points about Java LinkedHashSet class are:
● Contains unique elements only like HashSet.
● Duplicates not Allowed.
● Provides all optional set operations, and permits null elements.
● Maintains insertion order(this is the main Difference between HashSet
class and LinkedHashSet class).
● Heterogeneous objects Allowed.

Constructors of Java LinkedHashSet class


Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(Collection c) It is used to initialize the hash set by using the
elements of the collection c.
LinkedHashSet(int It is used initialize the capacity of the linkedhashset
capacity) to the given integer value capacity.
LinkedHashSet(int It is used to initialize both the capacity and the fill
capacity, float fillRatio) ratio (also called load capacity) of the hash set from
its argument.

Example: (This Example contains Homogeneous Objects by type casting with


String data type,here in this LinkedHashSet we can provide Heterogeneous
Objects also.)
import java.util.*;
class TestCollection10{
public static void main(String args[]){
LinkedHashSet<String> al=new LinkedHashSet<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
TreeSet class

Java TreeSet class implements the Set interface that uses a tree for
storage. It inherits AbstractSet class and implements NavigableSet interface.
The objects of the TreeSet class are stored in ascending order.
The important points about Java TreeSet class are:
● Contains unique elements only like HashSet.
● Access and retrieval times are quite fast.
● Maintains ascending order (Default Natural Sorting order(in case of
Numbers Ascending Order, in case of Strings Alphabetical Order).
● By sorting Collection Elements in Ascending Order internally JVM will
Process with Comparable Interface and compare the Elements with
compareTo() method for Sorting Ascending Order.
● By Using Customized Order we have to call Comparator Interface
through TreeSet class ,the Comparator Interface compares the Elements
with compare() method for customizing Sorting Order.
● TreeSet implements the NavigableSet interface (which was added by
Java SE 6),
Constructors of Java TreeSet class

Constructor Description
It is used to construct an empty tree set that will be
TreeSet() sorted in an ascending order according to the natural
order of the tree set.
TreeSet(Collection c) Itelements
is used to build a new tree set that contains the
of the collection c.
TreeSet(Comparator Itsortedis used to construct an empty tree set that will be
according to a given comparator (customized
comp) sorting order).
TreeSet(SortedSet ss) Itof istheused to build a TreeSet that contains the elements
given SortedSet.
Methods of Java TreeSet class

Method Description
boolean It is used to add all of the elements in the specified
addAll(Collection c) collection to this set.
boolean contains(Object It is used to return true if this set contains the
o) specified element.
boolean isEmpty() It is used to return true if this set contains no
elements.
boolean remove(Object It is used to remove the specified element from this set
o) if it is present.
void add(Object o) It is used to add the specified element to this set if it is
not already present.
void clear() It is used to remove all of the elements from this set.
Object first() It is used to return the first (lowest) element currently
in this sorted set.
Object last() It is used to return the last (highest) element currently
in this sorted set.
int size() It is used to return the number of elements in this set.
Examples

//Example: Ascending order of Example: (using Customized order by


Integer Numbers. String)
import java.util.*; import java.util.*;
public class TreeSetEX2 {
public class TreeSetEX { public static void main(String args[])
public static void main(String args[]) {
{ TreeSet m=new TreeSet(new
TreeSet m=new TreeSet(); MyComparatorset());
m.add("eca");
m.add(10); m.add("eae");
m.add(12); m.add("cse");
m.add(4); m.add("mech");
m.add(1245); System.out.println(m);
m.add(12); }
System.out.println(m); }
} class MyComparatorset implements
} Comparator
Output: {
[4, 10, 12, 1245] public int compare(Object
obj1,Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);
//insert return +1 for Insertion
Order,
// insert return -s2.compareTo(s1) for
Ascending order
}
}
Output:
[mech, eca, eae, cse]

// Example: Ascending order of Example: (using Customized order by


String. Integer Numbers)
import java.util.*; public class TreeSetEX3 {
public static void main(String args[])
public class TreeSetEXString { {
public static void main(String args[]) TreeSet m=new TreeSet(new
{ MyComparatorset1());
TreeSet m=new TreeSet();
m.add(10);
m.add("king"); m.add(12);
m.add("prince"); m.add(4);
m.add("Soldier"); m.add(1245);
m.add("Minister"); m.add(12);
m.add("Member"); System.out.println(m);
System.out.println(m);
}
} }
}
Output: class MyComparatorset1 implements
[Member, Minister, Soldier, king, Comparator
prince] {
public int compare(Object
obj1,Object obj2)
{
Integer i1=(Integer)obj1;
Integer i2=(Integer)obj2;
if(i1<i2)
{
return +1;
}
else if(i1>i2)
{
return -1;
}else
{
return 0;
}
}
}
Output:
[1245, 12, 10, 4]

Queue:
Java Queue interface orders the element in FIFO(First In First Out)
manner. In FIFO, the first element is removed first and the last element is
removed at last.
● JDK1.5 Version Enhancements (Queue Interface)
● It is the Child Interface of Collection.
● If we want to represent a group of individual objects prior to processing
this we should go for Queue.
For example:
● Before sending an SMS message, all mobile numbers we have to store in
some data Structures, in which order we added mobile no’s in the same
order will be delivered, for this First in First (FIFO) Requirement Queue is
the best Choice.
● Usually Queue follows FIFO order but based on our Requirement we can
implement our own Priority order also (PriorityQueue class).
● From JDK1.5 version onwards LinkedList class also implements Queue
Interface.
● LinkedList class based implementation of Queue always follows FIFO
order
Specific Methods:
Method Description
boolean add(object) It is used to insert the specified element into this queue
and return true upon success.
boolean It is used to insert the specified element into this
offer(object) queue.
It is used to retrieves and removes the head of this queue,
Object remove() , or returns Runtime Exception
NoSuchElementException
Object poll() It is used to retrieve and remove the head of this
queue, or returns null if this queue is empty.
It is used to retrieves, but does not remove, the head
Object element() of this queue, or returns Runtime Exception
NoSuchElementException
Object peek() It is used to retrieve, but does not remove, the head of
this queue, or returns null if this queue is empty.
PriorityQueue:
● If we want to represent a group of individual objects prior to processing
according to some Priority ,Then we should go for PriorityQueue class
● The Priority can be either Default natural sorting order(integers like
Ascending order and Strings like Alphabetical Order) or customized
sorting order defined by Comparator Interface.
● Insertion Order is not allowed and it is based on some Priority.
● Duplicated objects are not allowed.
● If we are depending on Default natural sorting order compulsory the
objects should be Homogeneous and comparable otherwise we will get
Runtime Exception i.e ClassCastException.
● If we are defining customized sorting order by comparator the objects
need not be Homogeneous and comparable.
● Null is not allowed even as the first element also.
Constructors:
// default 11 elements capacity and Default natural Sorting order (integers like
Ascending order and Strings like Alphabetical Order)
PriorityQueue pq=new PriorityQueue();
PriorityQueue pq=new PriorityQueue(int initialcapacity);
PriorityQueue pq=new PriorityQueue(int initialcapacity,Comparator c);
PriorityQueue pq=new PriorityQueue(SortedSet s);
PriorityQueue pq=new PriorityQueue(Collection c);
Example: Example2:
import java.util.*; //customized order
class ProiorityQueueEx import java.util.*;
{
public static void main(String args[]) class ProiorityQueueEx2
{ {
PriorityQueue pq=new PriorityQueue(); public static void main(String args[])
//System.out.println(pq.peek()); {
//null PriorityQueue pq=new
//System.out.println(pq.element()); PriorityQueue(15,new
//Runtime Exception MyComparator());
for(int i=0;i<=10;i++) q.offer(“A”);
{ q.offer(“Z”);
pq.offer(i); q.offer(“L”);
} q.offer(“B”);
System.out.println(pq); System.out.println(pq);
System.out.println(pq.peek()); {
System.out.println(pq.element()); }
} Class MyComparator implements
} Comparator
Output: {
[0,1,2,3,4,5,6,7,8,9,10] public int compare(Object obj1,Object
0 obj2)
[1,2,3,4,5,6,7,8,9,10] {
String s1=(String)obj1;
String s2=obj2.toString();
return –s1.compareTo(s2);
}
}
Output:
[Z,L,B,A]
Deque Interface

Java Deque Interface is a linear collection that supports element


insertion and removal at both ends. Deque is an acronym for "double ended
queue".
ArrayDeque class

The ArrayDeque class provides the facility of using deque and resizable-array.
It inherits AbstractCollection class and implements the Deque interface.
The important points about ArrayDeque class are:
● Unlike Queue, we can add or remove elements from both sides.
● Null elements are not allowed in the ArrayDeque.
● ArrayDeque is not thread safe, in the absence of external
synchronization.
● ArrayDeque has no capacity restrictions.
● ArrayDeque is faster than LinkedList and Stack.
Methods
Method Description
boolean It is used to insert the specified element into this deque and
add(object) return true upon success.
boolean It is used to insert the specified element into this deque.
offer(object)
Object remove() It is used to retrieve and remove the head of this deque.
Object poll() It is used to retrieve and remove the head of this deque, or
returns null if this deque is empty.
Object element() Itdeque.
is used to retrieve, but does not remove, the head of this

Object peek() Itdeque,


is used to retrieve, but does not remove, the head of this
or returns null if this deque is empty.

import java.util.*; // Example: offerFirst() and


public class ArrayDequeExample { pollLast()
public static void main(String[]
args) { import java.util.*;
//Creating Deque and adding public class DequeExample {
elements public static void main(String[] args)
Deque<String> deque = new {
ArrayDeque<String>(); Deque<String> deque=new
deque.add("Ravi"); ArrayDeque<String>();
deque.add("Vijay"); deque.offer("arvind");
deque.add("Ajay"); deque.offer("vimal");
//Traversing elements deque.add("mukul");
for (String str : deque) { deque.offerFirst("jai");
System.out.println(str); System.out.println("After
} offerFirst Traversal...");
} for(String s:deque){
} System.out.println(s);
Output: }
Ravi //deque.poll();
Vijay //deque.pollFirst();//it is same
Ajay as poll()
deque.pollLast();
System.out.println("After
pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Output:
After offerFirst Traversal...
jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal

Map Interface:
Java Map is an object that maps keys to values. A map
cannot contain duplicate keys: Each key can map to at most one value.
The Java platform contains three general-purpose Map implementations:
HashMap, TreeMap, and LinkedHashMap.

⮚ 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.
⮚ If we want to represent a group of objects with keys and value pairs then
we should go for Map Interface.
⮚ Both keys and values are objects only.
⮚ Each key value pair is called Entry, hence Map is considered as a
collection of Entry Objects.

methods of Map interface (Applicable for classes under Map Interface)


Method Description
Object put(Object key, Object It is used to insert an entry in this map.
value)
void putAll(Map map) It is used to insert the specified map in this
map.
Object remove(Object key) It is used to delete an entry for the specified
key.
Object get(Object key) It is used to return the value for the specified
key.
boolean containsKey(Object key) Itmap.
is used to search the specified key from this

Methods Description:
Object put(Object key, Object value):
⮚ To add one key value pair to the map,if the key is already present then
old value will be replaced with new value and returns Old value.
For Example:
m.put(102,”siva”);
m.put(102,”ggg”);
then output will be {102,”ggg”}.
Collection views of Map:
⮚ Set keySet(): It is used to return the Set view containing all the keys.
⮚ Collection values() : It is used to return the Collection of view containing
all the values.
⮚ Set entrySet() : It is used to return the Set view containing all the keys
and values.
Entry Interface:
⮚ A Map is a Group of Key Value pairs and Each Key value pair is called
Entry, hence Map is considered as collection of Entry Objects.
⮚ Without an existing Map object there is no chance of an Existing Entry
Object,hence Entry Interface is defined inside Map Interface.
⮚ Entry Specific Methods and we can apply only Entry Objects
● Object getKey(): to get of specified Entry Key
● Object getValue():to get of specified Entry value
● Object setValue():to set of specified Entry Value

HashMap Class

Java HashMap class implements the map interface by using a hashtable. It


inherits AbstractMap class and implements Map interface.
The important points about Java HashMap class are:
● A HashMap contains values based on the key (Heterogeneous keys and
values may be allowed).
● It contains only unique elements,duplicate keys not Allowed but values
may be duplicate allowed.
● It may have one null key and multiple null values.
● It maintains no order.(by using Hash Table Concept).
Constructors of Java HashMap class
Constructor Description
HashMap() It is used to construct a default HashMap.(Default
capacity 16)
HashMap(Map m) It is used to initialize the hash map by using the
elements of the given Map object m.
HashMap(int capacity) Ittheisgiven
used to initialize the capacity of the hash map to
integer value, capacity.
HashMap(int capacity, Ittheishashmap
used to initialize both the capacity and fill ratio of
by using its arguments. (default fill ratio
float fillRatio) 0.75)
Methods of Java HashMap class
Method Description
void clear() It is used to remove all of the mappings from this
map.
boolean containsKey(Object It is used to return true if this map contains a
key) mapping for the specified key.
boolean containsValue(Object It is used to return true if this map maps one or
value) more keys to the specified value.
boolean isEmpty() It is used to return true if this map contains no
key-value mappings.
Set entrySet() It is used to return a collection view of the
mappings contained in this map.
Set keySet() It is used to return a set view of the keys
contained in this map.
Object put(Object key, Object It is used to associate the specified value with the
value) specified key in this map.
int size() It is used to return the number of key-value
mappings in this map.
Collection values() It is used to return a collection view of the values
contained in this map.

Example:
import java.util.*;
public class HashMapEX {
public static void main(String args[])
{
HashMap m=new HashMap();
m.put("101","A");
m.put("102","B");
m.put("103",1000);
m.put("104",'v');
System.out.println(m);
m.put("101",455);
System.out.println(m);
Set s=m.keySet();
System.out.println(s);
Collection c=m.values();
System.out.println(c);
Set s1=m.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
while(itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey());
if(m1.getKey().equals("101"))
{
m1.setValue(500000);
}
}
System.out.println(m);
}
}
Output:
{101=A, 102=B, 103=1000, 104=v}
{101=455, 102=B, 103=1000, 104=v}
[101, 102, 103, 104]
[455, B, 1000, v]
[101=455, 102=B, 103=1000, 104=v]
101
102
103
104
{101=500000, 102=B, 103=1000, 104=v}
LinkedHashMap:
It is the Child class of Hash Map it is exactly same as HashMap including
Methods and Constructors except the following
The important points about Java LinkedHashMap class are:
● LinkedHashMap class is a combination of Hash table and Linked list
(Hybrid DataStructure) implementation of the Map interface
● It maintains Insertion order.
Constructors of Java LinkedHashMap class
Constructor Description
LinkedHashMap() It is used to construct a default
LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the
given capacity.
LinkedHashMap(int capacity, It is used to initialize both the capacity and the
float fillRatio) fillRatio.
LinkedHashMap(Map m) It is used to initialize the LinkedHashMap with
the elements from the given Map class m.

Methods of Java LinkedHashMap class


⮚ Same as methods in HashMap.
Example:
import java.util.*;
public class HashMapEX {
public static void main(String args[])
{
LinkedHashMap m=new LinkedHashMap();
m.put("cse","A");
m.put("ece","B");
m.put("eee",1000);
m.put("mech",'v');
System.out.println(m);
m.put("cse",455);
System.out.println(m);
Set s=m.keySet();
System.out.println(s);
Collection c=m.values();
System.out.println(c);
Set s1=m.entrySet();
System.out.println(s1);
Iterator itr=s1.iterator();
while(itr.hasNext())
{
Map.Entry m1=(Map.Entry)itr.next();
System.out.println(m1.getKey());
if(m1.getKey().equals("101"))
{
m1.setValue(500000);
}
}
System.out.println(m);
}
}
Output:
{cse=A, ece=B, eee=1000, mech=v}
{cse=455, ece=B, eee=1000, mech=v}
[cse, ece, eee, mech]
[455, B, 1000, v]
[cse=455, ece=B, eee=1000, mech=v]
cse
ece
eee
mech
{cse=455, ece=B, eee=1000, mech=v}

SortedMap Interface:
⮚ SortedMap is the Child Interface of Map Interface.
⮚ If we want to represent a group of key value pairs according to some
sorting order of keys then we should go for SortedMap.
⮚ Sorting is based on the key but not based on Value.
⮚ Sorted map defines the following specific methods

Object firstKey() It is used to return the first (lowest) key


currently in this sorted map.
Object lastKey() It is used to return the last (highest) key
currently in this sorted map.
Object get(Object key) It is used to return the value to which this
map maps the specified key.
Object remove(Object key) It is used to remove the mapping for this key
from this TreeMap if present.
SortedMap tailMap(Object Key) Itkeyreturns Sorted map which is greater than
sortedMap Object headMap(key) It returns Sorted map which is less than key
SortedMap subMap(Object key1 It returns Sorted map which is greater than
,Object key2) key1 but less than key2
Comparator comparator() To returns Comparator Object for Customized
order
TreeMap class

TreeMap class implements the Map interface by using a tree. It provides an


efficient means of storing key/value pairs in sorted order.
The important points about Java TreeMap class are:
⮚ Insertion order is not allowed and it is based on some sorting of keys.
⮚ Duplicate keys are not allowed but values can be duplicated.
⮚ If we are depending on Default Natural Sorting order (as integers
ascending order, as String Alphabetical Order) then Keys Should be
Homogenous and Comparable Interface, otherwise Runtime Exception
raised as ClassCastException.
⮚ If we are depending on Customizing order then Keys may be
Homogenous or Heterogenous and should be called Comparator
Interface.
⮚ if we are depending on Default Natural Sorting order or Customized
Sorting order there are no restrictions for values ,we can take
Heterogeneous non Comparable Objects also.
⮚ For non-empty TreeMap if we are trying to insert an Entry with null Key
then we will get Runtime Exception NullPointerException
⮚ For empty TreeMap as the First Entry with null Key is allowed but after
inserting the entry if we are trying insert any other entry then we will get
Runtime Exception NullPointerException
⮚ The null Acceptance rule applicable until jdk1.6 version,for jdk1.7
version null is not allowed for keys.
⮚ For values we can use null any number of times in jdk1.6 or jdk1.7
versions.
Constructors of Java TreeMap class
TreeMap() It is used to construct an empty tree map that will be
sorted using the natural order of its key.
TreeMap(Comparator Itwillis be
used to construct an empty tree-based map that
sorted using the comparator comp (customized
comp) sorting order).
It is used to initialize a treemap with the entries from
TreeMap(Map m) m, which will be sorted using the natural order of the
keys.
TreeMap(SortedMap IttheisSortedMap
used to initialize a treemap with the entries from
sm, which will be sorted in the same
sm) order as sm.
Methods of Java TreeMap class
Method Description
boolean containsKey(Object It is used to return true if this map contains a
key) mapping for the specified key.
boolean containsValue(Object It is used to return true if this map maps one or
value) more keys to the specified value.
Object firstKey() It is used to return the first (lowest) key currently
in this sorted map.
Object get(Object key) It is used to return the value to which this map
maps the specified key.
Object lastKey() It is used to return the last (highest) key currently
in this sorted map.
Object remove(Object key) Itthisis used to remove the mapping for this key from
TreeMap if present.
void putAll(Map map) It is used to copy all of the mappings from the
specified map to this map.
Set entrySet() It is used to return a set view of the mappings
contained in this map.
int size() It is used to return the number of key-value
mappings in this map.
Collection values() It is used to return a collection view of the values
contained in this map.

Examples:
//DefaultNatureSorting order for //customized order for Homogenous
Hetrogenous keys keys
import java.util.*; import java.util.*;
class TestCollection15{ public class TreeMapEX2 {
public static void main(String public static void
args[]){ main(String args[])
TreeMap<Integer,String> hm=new {
TreeMap<Integer,String>(); TreeMap m=new
hm.put(100,"Amit"); TreeMap(new MyComparator());
hm.put(102,"Ravi");
hm.put(101,"Vijay"); m.put("eca","B");
hm.put(103,"Rahul"); m.put("eae",1000);
for(Map.Entry m:hm.entrySet()){ m.put("cse","A");
System.out.println(m.getKey()+" m.put("mech",'v');
"+m.getValue()); System.out.println(m);
}
}
} }
Output:
}
100 Amit class MyComparator
101 Vijay implements Comparator
102 Ravi {
103 Rahul public int compare(Object
obj1,Object obj2)
{
String s1=obj1.toString();
String s2=obj2.toString();
return s2.compareTo(s1);
}
}
Output:
{mech=v, eca=B, eae=1000, cse=A}
//DefaultNatureSorting order for //customized order for Hetrogenous
Hetrogenous keys keys
import java.util.*; import java.util.*;
public class TreeMapEX { public class TreeMapEX2 {
public static void main(String args[]) public static void main(String
{ args[])
TreeMap m=new TreeMap(); {
TreeMap m=new
m.put("eca","B"); TreeMap(new MyComparator());
m.put("eae",1000);
m.put("cse","A"); m.put(12,"B");
m.put("mech",'v'); m.put(55,1000);
System.out.println(m); m.put("A","A");
m.put("cse",455); m.put("45",'v');
System.out.println(m); System.out.println(m);
Set s=m.keySet();
System.out.println(s);
Collection c=m.values(); }
System.out.println(c);
Set s1=m.entrySet(); }
System.out.println(s1); class MyComparator implements
Iterator itr=s1.iterator(); Comparator
while(itr.hasNext()) {
{ public int compare(Object
Map.Entry obj1,Object obj2)
m1=(Map.Entry)itr.next(); {
String s1=obj1.toString();
System.out.println(m1.getKey()); String s2=obj2.toString();
return s2.compareTo(s1);
if(m1.getKey().equals("cse")) }
{ }
m1.setValue(500000); Output:
} {A=A, 55=1000, 45=v, 12=B}
}
System.out.println(m);

}
}
Output:
{cse=A, eae=1000, eca=B, mech=v}
{cse=455, eae=1000, eca=B, mech=v}
[cse, eae, eca, mech]
[455, 1000, B, v]
[cse=455, eae=1000, eca=B, mech=v]
cse
eae
eca
mech
{cse=500000, eae=1000, eca=B,
mech=v}

The Legacy Classes and Interfaces


● Hashtable class
● Properties
HashTable:
⮚ Hashtable class implements a hashtable, which maps keys to values.
⮚ It inherits Dictionary class and implements the Map interface.
⮚ Insertion Order is not allowed and it is based on the Hash code of
Keys.
⮚ Duplicate keys are not allowed and values can be duplicated.
⮚ Heterogeneous Objects are allowed for both Keys and Values.
⮚ Null is not allowed for both key and values, otherwise Runtime
Exception raised NullPointerException.
⮚ Every method present in Hashtable is Synchronized and hence
Hashtable is Thread Safe

Constructors of Java Hashtable class


Constructor Description
Hashtable() It is the default constructor of hash table it instantiates
the Hashtable class.(Default initial capacity 11)
It is used to accept an integer parameter and creates a
Hashtable(int size) hash table that has an initial size specified by integer
value size.
Hashtable(int size, It is used to create a hash table that has an initial size
float fillRatio) specified by size and a fill ratio specified by fillRatio.

Example:
//may take the values in buckets as Top to Bottom.
//if any bucket having 2 or more elements then
// it will take from right to left
import java.util.*;
public class HashTableEx {
public static void main(String args[])
{
Hashtable h=new Hashtable();
h.put(new Temp(5),"d");
h.put(new Temp(2),"f");
h.put(new Temp(6),"g");
h.put(new Temp(15),"e");
h.put(new Temp(23),"w");
h.put(new Temp(16),"hhh");
System.out.println(h);
}
}
class Temp
{
int i;
Temp(int i)
{
this.i=i;
}
public int hashCode()
{
return i;
}
public String toString()
{
return i+"";
}
}
Output:
{6=g, 16=hhh, 5=d, 15=e, 2=f, 23=w}

Properties class in Java


The properties object contains key and value pair both as a string. The
java.util.Properties class is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties
class provides methods to get data from properties file and store data into
properties file. Moreover, it can be used to get properties of system.
⮚ In normal Map Interface key and value can be any type ,but in case of
Properties key and value should be String Type
Constructor:
Properties p=new Properties();
forExample:
⮚ In our program if anything which changes frequently (like
username,password,mailId,mobileno etc.) are not recommended to hard
coding(keeping values directly) in java programing, if there any change to
reflect that change recompilation , rebuild and redeploy Application are
required, even sometimes Server Restart also Required which creates a
big Business Impact to the Client.
⮚ We can rectify this problem by using Properties File such Type of Variable
Things we have to configure in the Properties file, from the properties file
we have to read into java program and we can use those properties the
main advantage of this approach is there is a change in properties file ,to
reflect that change just redeployment is enough which won’t create any
business impact to the client.
Methods of Properties class
Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream
object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String sets the property in the properties
value) object.
public void store(Writer w, String writers the properties in the writer
comment) object.
public void store(OutputStream os, String writes the properties in the
comment) OutputStream object.
Example:
package Collections;
import java.util.*;
import java.io.*;
public class PropertiesEx {
public static void main(String args[])throws Exception
{
Properties p=new Properties();
FileInputStream fis=new FileInputStream("abc.properties");
p.load(fis);
System.out.println(p);
String s=p.getProperty("pass");
System.out.println(s);
p.setProperty("server", "osci");
FileOutputStream fos=new FileOutputStream("abc.properties");
p.store(fos, "updated by me"); } }
In abc.properties file
user=scott
pass=tiger
output: Output in abc.properties file
{user=scott, pass=tiger} #updated by me
Tiger #Tue Oct 30 23:39:46 PDT 2018
user=scott
pass=tiger
server=osci
Accessing a Collection via an Iterator
you might want to display each element. One way to do this is to employ
an iterator, which is an object that implements either the Iterator or the
ListIterator interface. Iterator enables you to cycle through a collection,
obtaining or removing elements. ListIterator extends Iterator to allow
bidirectional traversal of a list, and the modification of elements. Iterator and
ListIterator are generic interfaces which are declared as shown here:
interface Iterator<E>
interface ListIterator<E>
Using an Iterator
Each of the collection classes provides an iterator( ) method that returns
an iterator to the start of the collection. By using this iterator object, you can
access each element in the collection, one element at a time. In general, to use
an iterator to cycle through the contents of a collection,follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s
iterator( )
method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long
as hasNext( )
returns true.
3. Within the loop, obtain each element by calling next( ).
Using an ListIterator
list iterator gives you the ability to access the collection in either the
forward
or backward direction and lets you modify an element. Otherwise,
ListIterator is used just like Iterator.
Example:
// Demonstrate iterators.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// Use an iterator to display contents of al.
System.out.print("Original contents of al: ");
Iterator<String> itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Modify objects being iterated.
ListIterator<String> litr = al.listIterator();
while(litr.hasNext()) {
String element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
String element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// Now, display the list backwards.
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
String element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
The output is shown here:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
The For-Each Alternative to Iterators

For-each is another array traversing technique like for loop, while loop,
do-while loop introduced in Java5.
● It starts with the keyword for like a normal for-loop.
● Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a
colon, which is then followed by the array name.
● In the loop body, you can use the loop variable you created rather than
using an indexed array element.
● It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList)

Syntax:
for (type var : array)
{
statements using var;
}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
Example:
// Use the for-each for loop to cycle through a collection.
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Original contents of vals: ");
for(int v : vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}
The output from the program is shown here:
Original contents of vals: 1 2 3 4 5
Sum of values: 15
String Tokenizer
The java.util.StringTokenizer class allows you to break a string into
tokens. It is a simple way to break strings.
It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like the StreamTokenizer class. We will discuss the
StreamTokenizer class in the I/O chapter.
Constructors of StringTokenizer class
There are 3 constructors defined in the StringTokenizer class.
Constructor Description
StringTokenizer(String str) creates a StringTokenizer with a specified string.
StringTokenizer(String str, creates StringTokenizer with specified string and
String delim) delimiter.
StringTokenizer(String str, creates StringTokenizer with specified string,
String delim, boolean delimiter and returnValue. If the return value is
returnValue) true, delimiter characters are considered to be
tokens. If it is false, delimiter characters serve to
separate tokens.
Methods of StringTokenizer class
The 6 useful methods of StringTokenizer class are as follows:
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer
object.
String nextToken(String returns the next token based on the delimiter.
delim)
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.
Simple example of StringTokenizer class
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
Output:my
name
is
khan
Example of nextToken(String delim) method of StringTokenizer class
import java.util.*;
public class Test {
public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}
Output:Next token is : my

BitSet Class
The Java BitSet class implements a vector of bits. The BitSet grows
automatically as more bits are needed. The BitSet class comes under the
java.util package. The BitSet class extends the Object class and provides the
implementation of Serializable and Cloneable interfaces.
Each component of the bit set contains at least one Boolean value. The
contents of one BitSet may be changed by another BitSet using logical AND,
logical OR and logical exclusive OR operations. The index of bits of the BitSet
class is represented by positive integers.
Each element of bits contains either true or false value. Initially, all bits
of a set have a false value. A BitSet is not safe for multithreaded use without
using external synchronization.
The BitSet class creates a special type of array that holds bit values. This
array can increase in size as needed. This makes it similar to a vector of bits.
The BitSet constructors are shown here:
BitSet( )
BitSet(int size)
The first version creates a default object. The second version allows you to
specify its initial
size (that is, the number of bits that it can hold). All bits are initialized to zero.
Example:
Here is an example that demonstrates BitSet:
// BitSet Demonstration.
import java.util.BitSet;
class BitSetDemo {
public static void main(String args[]) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
// set some bits
for(int i=0; i<16; i++) {
if((i%2) == 0) bits1.set(i);
if((i%5) != 0) bits2.set(i);
}
System.out.println("Initial pattern in bits1: ");
System.out.println(bits1);
System.out.println("\nInitial pattern in bits2: ");
System.out.println(bits2);
// AND bits
bits2.and(bits1);
System.out.println("\nbits2 AND bits1: ");
System.out.println(bits2);
// OR bits
bits2.or(bits1);
System.out.println("\nbits2 OR bits1: ");
System.out.println(bits2);
// XOR bits
bits2.xor(bits1);
System.out.println("\nbits2 XOR bits1: ");
System.out.println(bits2);
}
}
The output from this program is shown here. When toString( ) converts a
BitSet object to its
string equivalent, each set bit is represented by its bit position. Cleared bits are
not shown.
Initial pattern in bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
Initial pattern in bits2:
{1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14}
bits2 AND bits1:
{2, 4, 6, 8, 12, 14}
bits2 OR bits1:
{0, 2, 4, 6, 8, 10, 12, 14}
bits2 XOR bits1:
{}
Date:
The Date class encapsulates the current date and time. The Date class
encapsulates the current date and time. Before beginning our examination of
Date, it is important to point out that it has changed substantially from its
original version defined by Java 1.0. When Java 1.1 was released, many of the
functions carried out by the original Date class were moved into the Calendar
and DateFormat classes, and as a result, many of the original 1.0 Date
methods were deprecated. Since the deprecated 1.0 methods should not be
used for new code, they are not described here.
Date supports the following constructors:
Date( )
Date(long millisec)
The first constructor initializes the object with the current date and time. The
second constructor
accepts one argument that equals the number of milliseconds that have
elapsed since midnight,
January 1, 1970.
Date also
implements the Comparable interface.
Constructors
No. Constructor Description
1) Date() Creates a date object representing current date and
time.
2) Date(long
milliseconds)
Creates a date object for the given milliseconds since
January 1, 1970, 00:00:00 GMT.

java.util.Date Methods
No. Method Description

1) boolean after(Date date) tests if the current date is after the given
date.

2) boolean before(Date date) tests if the current date is before the given
date.
3) Object clone() returns the clone object of the current date.

4) int compareTo(Date date) compares the current date with the given
date.

5) boolean equals(Date date) compares current date with the given date for
equality.

6) static Date from(Instant


instant)
returns an instance of Date object from
Instant date.

7) long getTime() returns the time represented by this date


object.

8) int hashCode() returns the hash code value for this date
object.

9) void setTime(long time) changes the current date and time to a given
time.
10) Instant toInstant() converts current date into Instant object.
11) String toString() converts this date into an Instant object.

Example:
import java.util.Date.*;
public class UtilDateExample1{
public static void main(String args[]){
java.util.Date date=new Date();
System.out.println(date);
}}
Output:
Mon Nov 05 15:06:04 IST 2018
Example2:
import java.util.Date.*;
public class UtilDateExample1{
public static void main(String args[]){
java.util.Date date=new Date();
System.out.println(date);
}}
Output:
Mon Nov 05 15:05:41 IST 2018

Calendar Class:

Java Calendar class is an abstract class that provides methods for


converting data between a specific instant in time and a set of calendar fields
such as MONTH, YEAR, HOUR, etc. It inherits Object class and implements the
Comparable interface.
Calendar class declaration
Let's see the declaration of java.util.Calendar class.
1. public abstract class Calendar extends Object
2. implements Serializable, Cloneable, Comparable<Calendar>
Example:
import java.util.Calendar;
public class CalendarExample1 {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("The current date is : " + calendar.getTime());
calendar.add(Calendar.DATE, -15);
System.out.println("15 days ago: " + calendar.getTime());
calendar.add(Calendar.MONTH, 4);
System.out.println("4 months later: " + calendar.getTime());
calendar.add(Calendar.YEAR, 2);
System.out.println("2 years later: " + calendar.getTime());
}
}
Output:
The current date is : Mon Nov 05 15:08:47 IST 2018
15 days ago: Sun Oct 21 15:08:47 IST 2018
4 months later: Thu Feb 21 15:08:47 IST 2019
2 years later: Sun Feb 21 15:08:47 IST 2021

Random:
The Random class is a generator of pseudorandom numbers. These are
called pseudorandom numbers because they are simply uniformly distributed
sequences. Random defines the following constructors:
Random( )
Random(long seed)
The first version creates a number generator that uses the current time as the
starting, or seed,
value. The second form allows you to specify a seed value manually.
Methods Description
doubles() Returns an unlimited stream of pseudorandom double values.
ints() Returns an unlimited stream of pseudorandom int values.
longs() Returns an unlimited stream of pseudorandom long values.
next() Generates the next pseudorandom number.

nextBoolean() Returns the next uniformly distributed pseudorandom boolean


value from the random number generator's sequence

nextByte() Generates random bytes and puts them into a specified byte
array.

nextDouble() Returns the next pseudorandom Double value between 0.0 and
1.0 from the random number generator's sequence
Returns the next uniformly distributed pseudorandom Float
nextFloat() value between 0.0 and 1.0 from this random number
generator's sequence
Returns the next pseudorandom Gaussian double value with
nextGaussian() mean 0.0 and standard deviation 1.0 from this random number
generator's sequence.

nextInt() Returns a uniformly distributed pseudorandom int value


generated from this random number generator's sequence

nextLong() Returns the next uniformly distributed pseudorandom long


value from the random number generator's sequence.

setSeed() Sets the seed of this random number generator using a single
long seed.

Example:
import java.util.Random;
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
System.out.println("Longs value : "+random.longs());
// Returns the next pseudo random boolean value
boolean val = random.nextBoolean();
System.out.println("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
random.nextBytes(bytes);
System.out.print("Random bytes = ( ");
for(int i = 0; i< bytes.length; i++)
{
System.out.printf("%d ", bytes[i]);
}
System.out.print(")");
}
}

Output:
Longs value : java.util.stream.LongPipeline$Head@50cbc42f
Random boolean value : false
Random bytes = ( -127 74 73 -22 -49 -38 -103 15 -27 -64 )
Formatter
● With the release of JDK 5, Java added a capability long desired by
programmers.
● Java has offered a rich and varied API, but it has not always offered an
easy way to create formatted text output, especially for numeric values.
● Classes such as NumberFormat, DateFormat, and MessageFormat
provided by earlier versions of Java do have useful formatting
capabilities, but they were not especially convenient to use.
● At the core of Java’s support for creating formatted output is the
Formatter class. It provides format conversions that let you display
numbers, strings, and time and date in virtually any format you like. It
operates in a manner similar to the C/C++ printf( ) function, which
means that if you are familiar with C/C++, then learning to use
Formatter will be very easy. It also further streamlines the conversion of
C/C++ code to Java. If you are not familiar with C/C++, it is still quite
easy to format data.
Constructors
The Formatter class defines many constructors, which enable you to construct
a Formatter in a variety of ways. Here is a sampling:
Formatter( )
Formatter(Appendable buf)
Formatter(Appendable buf, Locale loc)
Formatter(String filename)
throws FileNotFoundException
Formatter(String filename, String charset)
throws FileNotFoundException, UnsupportedEncodingException
Formatter(File outF)
throws FileNotFoundException
Formatter(OutputStream outStrm)

Formatter Methods
Method Description
Closes the invoking Formatter. This
causes any resources used by the
object to be released. After a
void close( ) Formatter has been closed, it cannot
be reused. An attempt to use a closed
Formatter results in a
FormatterClosedException.
Flushes the format buffer. This causes
any output currently in the buffer to
void flush( ) be written to the destination. This
applies mostly to a Formatter tied to a
file.
Formatter format(String fmtString, Formats the arguments passed via
Object ... args) args according to the format specifiers
contained in fmtString. Returns the
invoking object.
Formats the arguments passed via
Formatter format(Locale loc, args according to the format specifiers
String fmtString, contained in fmtString. The locale
Object ... args) specified by loc is
used for this format. Returns the
invoking object.
If the underlying object that is the
destination for output throws an
IOException ioException( ) IOException, then this exception is
returned. Otherwise,
null is returned.
Locale locale( ) Returns the invoking object’s locale.
Returns a reference to the underlying
Appendable out( ) object that is the destination for
output.
String toString( ) Returns a String containing the
formatted output.
Formatting Numbers
● To format an integer in decimal format, use %d. To format a
floating-point value in decimal format, use %f.
● To format a floating-point value in scientific notation, use %e. Numbers
● represented in scientific notation take this general form:
● x.dddddde+/–yy
● The %g format specifier causes Formatter to use either %f or %e,
whichever is shorter.
● The following program demonstrates the effect of the %g format specifier:
Example:
// Demonstrate the %g format specifier.
import java.util.*;
class FormatDemo2 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
for(double i=1000; i < 1.0e+10; i *= 100) {
fmt.format("%g ", i);
System.out.println(fmt);
}
}
}
It produces the following output:
1000.000000
1000.000000 100000.000000
1000.000000 100000.000000 1.000000e+07
1000.000000 100000.000000 1.000000e+07 1.000000e+09
Scanner
● Scanner is the complement of Formatter. Added by JDK 5, Scanner
reads formatted input and converts it into its binary form.
● Although it has always been possible to read formatted input, it required
more effort than most programmers would prefer. Because of the
addition
● of Scanner, it is now easy to read all types of numeric values, strings,
and other types of data,
● whether it comes from a disk file, the keyboard, or another source.
● Scanner can be used to read input from the console, a file, a string, or
any source that implements the Readable interface or
ReadableByteChannel.
For example,
You can use Scanner to read a number from the keyboard and assign its
value to a variable. As you will see, given its power, Scanner is surprisingly
easy to use.
Constructors
In general, a Scanner can be created for a String, an InputStream, a File, or
any object that implements the Readable or ReadableByteChannel interfaces.
Here are some examples.
The following sequence creates a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
This works because FileReader implements the Readable interface. Thus, the
call to the constructor resolves to Scanner(Readable).
Java Scanner class comes under the java.util package. Java has various ways
to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace by default. It provides many methods to read and parse various
primitive values.
Java Scanner class is widely used to parse text for string and primitive types
using a regular expression.
Java Scanner class extends Object class and implements Iterator and
Closeable interfaces.
Examples:
Some Scanner Examples
The addition of Scanner to Java makes what was formerly a tedious task into
an easy one.
To understand why, let’s look at some examples.
The following program averages a list of numbers entered at the keyboard:
// Use Scanner to compute an average of the values.
import java.util.*;
class AvgNums {
public static void main(String args[]) {
Scanner conin = new Scanner(System.in);
int count = 0;
double sum = 0.0;
System.out.println("Enter numbers to average.");
// Read and sum numbers.
while(conin.hasNext()) {
if(conin.hasNextDouble()) {
sum += conin.nextDouble();
count++;
}
else {
String str = conin.next();
if(str.equals("done")) break;
else {
System.out.println("Data format error.");
return;
}
}
}
System.out.println("Average is " + sum / count);
}
}

The program reads numbers from the keyboard, summing them in the process,
until the user enters the string “done”. It then stops input and displays the
average of the numbers.
Here is a sample run:
Enter numbers to average.
1.2
2
3.4
4
done
Average is 2.65

You might also like