OOPJ Module 4
OOPJ Module 4
Prepared By :
Prepared By :
[Link], HOD
[Link] SELVA RAJ, AP /CSE
/[Link],
AP/CSE
UNIT 4
COLLECTIONS IN JAVA
Before Collections:
There are 4 ways to store values in JVM
1. Using variables : can store only one value
2. Using class object : can store multiple fixed number of values of different types
3. Using array object : can store multiple fixed number of values of same type
4. Using collections : can store multiple objects of same and different types
without size limitation
Collection:
● In general terms a collection is a “group of objects”
● The Collection in Java is a framework that provides a facility to store and
manipulate the group of objects.
● A Collection is a group of individual objects represented as a single unit
● Collection Framework is a set of classes and interfaces that implement
commonly reusable collection data structures.
● It works in the manner of a library.
● The ‘[Link]’ package contains all the classes and interfaces for the
Collection framework.
● It provided methods to perform all type of operations on data such as
searching, sorting, insertion, manipulation, and deletion.
● Java Collection framework provides many interfaces such as Set, List, etc.
and classes such as ArrayList, etc.
Map
Hash Table 0
0 0
Hash Table
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words, we can
say that the Collection interface builds the foundation on which the collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection interface.
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but there
is no size limit. We can add or remove elements anytime. So, it is much more flexible than the
traditional array. It is found in the [Link] package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements the List interface so
we can use all the methods of the List interface here. The ArrayList maintains the insertion order
internally.
Syntax :
Arraylist<Datatype> Arraylist_Var = new Arraylist<Datatype>();
Constructors of ArrayList
Constructor Description
ArrayList(Collection<? extends E> It is used to build an array list that is initialized with the elements of the
c) collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Methods of ArrayList
Method Description
void add(int index, E element) It is used to insert the specified element at the specified position in
a list.
boolean add(E e) It is used to append the specified element at the end of a list.
boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified collection
c) to the end of this list, in the order that they are returned by the
specified collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection,
extends E> c) starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
E get(int index) It is used to fetch the element from the particular position of the
list.
Iterator()
listIterator()
int lastIndexOf(Object o) It is used to return the index in this list of the last 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.
<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list
in the correct order.
boolean contains(Object o) It returns true if the list contains the specified element.
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in
the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.
boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that satisfies the
filter) given predicate.
protected void removeRange(int It is used to remove all the elements lies within the given range.
fromIndex, int toIndex)
void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified
operator) element.
void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the
specified collection.
E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.
void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the
specified comparator.
List<E> subList(int fromIndex, int It is used to fetch all the elements that lies within the given range.
toIndex)
int size() It is used to return the number of elements present in the list.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be the
list's current size.
Java new generic collection allows you to have only one type of object in a collection. Now it is
type-safe, so typecasting is not required at runtime.
import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){ Output: Mango
Apple
ArrayList<String> list=new ArrayList<String>();//Creating arraylist Banana
[Link]("Mango");//Adding object in arraylist Grapes
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object
[Link](list);
}
}
Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.
Syntax:
LinkedList(Collection<? It is used to construct a list containing the elements of the specified collection,
extends E> c) in the order, they are returned by the collection's iterator.
boolean add(E e) It is used to append the specified element to the end of a list.
void add(int index, E element) It is used to insert the specified element at the specified position index
in a list.
boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to
E> c) the end of this list, in the order that they are returned by the specified
collection's iterator.
boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to
E> c) the end of this list, in the order that they are returned by the specified
collection's iterator.
boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection, starting
John Selva Raj
Mohan Babu University
void addFirst(E e) It is used to insert the given element at the beginning of a list.
void addLast(E e) It is used to append the given element to the end of a list.
Iterator<E> descendingIterator() It is used to return an iterator over the elements in a deque in reverse
sequential order.
E get(int index) It is used to return the element at the specified position in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain any element.
ListIterator<E> listIterator(int index) It is used to return a list-iterator of the elements in proper sequence,
starting at the specified position in the list.
boolean offer(E e) It adds the specified element as the last element of a list.
E peekFirst() It retrieves the first element of a list or returns null if a list is empty.
E peekLast() It retrieves the last element of a list or returns null if a list is empty.
E pollFirst() It retrieves and removes the first element of a list, or returns null if a
list is empty.
E pollLast() It retrieves and removes the last element of a list, or returns null if a list
is empty.
John Selva Raj
Mohan Babu University
E remove(int index) It is used to remove the element at the specified position in a list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element in a
list.
boolean It removes the last occurrence of the specified element in a list (when
removeLastOccurrence(Object o) traversing the list from head to tail).
E set(int index, E element) It replaces the element at the specified position in a list with the
specified element.
Object[] toArray() It is used to return an array containing all the elements in a list in
proper sequence (from first to the last element).
<T> T[] toArray(T[] a) It returns an array containing all the elements in the proper sequence
(from first to the last element); the runtime type of the returned array
is that of the specified array.
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
John Selva Raj
Mohan Babu University
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number
of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is
found in the [Link] package and implements the List interface, so we can use all the methods of List
interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to
use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in
such case.
The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and
throws the ConcurrentModificationException.
Syntax:
SN Constructor Description
2) vector(int initialCapacity) It constructs an empty vector with the specified initial capacity and
with its capacity increment equal to zero.
3) vector(int initialCapacity, int It constructs an empty vector with the specified initial capacity and
capacityIncrement) capacity increment.
4) Vector( Collection<? extends E> c) It constructs a vector that contains the elements of a collection c.
SN Method Description
2) addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.
3) addElement() It is used to append the specified component to the end of this vector. It
John Selva Raj
Mohan Babu University
8) containsAll() It returns true if the vector contains all of the elements in the specified collection.
9) copyInto() It is used to copy the components of the vector into the specified array.
12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.
13) equals() It is used to compare the specified object with the vector for equality.
15) forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.
18) indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
19) insertElementAt() It is used to insert the specified object as a component in the given vector at the
specified index.
21) iterator() It is used to get an iterator over the elements in the list in proper sequence.
23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.
25) remove() It is used to remove the specified element from the vector. If the vector does not
John Selva Raj
Mohan Babu University
26) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.
27) removeAllElements() It is used to remove all elements from the vector and set the size of the vector to
zero.
28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.
30) removeIf() It is used to remove all of the elements of the collection that satisfy the given
predicate.
31) removeRange() It is used to delete all of the elements from the vector whose index is between
fromIndex, inclusive and toIndex, exclusive.
32) replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.
33) retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.
34) set() It is used to replace the element at the specified position in the vector with the
specified element.
35) setElementAt() It is used to set the component at the specified index of the vector to the
specified object.
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the specified
Comparator.
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the
list.
40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive, and
toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this vector in correct
order.
43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.
import [Link].*;
//Create a vector
[Link]("Tiger");
[Link]("Lion");
[Link]("Dog");
[Link]("Elephant");
[Link]("Rat");
[Link]("Cat");
[Link]("Deer");
Output:
Java HashSet
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.
Syntax:
A list can contain duplicate elements whereas Set contains unique elements only.
2) HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer
value capacity. The capacity grows automatically as elements are added to
the HashSet.
3) HashSet(int capacity, float It is used to initialize the capacity of the hash set to the given integer
loadFactor) value capacity and the specified load factor.
4) HashSet(Collection<? It is used to initialize the hash set by using the elements of the collection
extends E> c) c.
1) boolean add(E e) It is used to add the specified element to this set if it is not
already present.
2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet instance: the
elements themselves are not cloned.
4) boolean contains(Object It is used to return true if this set contains the specified element.
o)
6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.
7) boolean remove(Object It is used to remove the specified element from this set if it is
o) present.
Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.
import [Link].*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link](); Output: Five
while([Link]()) One
Four
{ Two
[Link]([Link]()); Three
}
}
}
John Selva Raj
Mohan Babu University
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class
and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending
order.
Syntax:
TreeSet() It is used to construct an empty tree set that will be sorted in ascending order
according to the natural order of the tree set.
TreeSet(Collection<? extends It is used to build a new tree set that contains the elements of the collection c.
E> c)
boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified
collection to this set.
SortedSet headSet(E toElement) It returns the group of elements that are less than the
specified element.
NavigableSet headSet(E toElement, boolean inclusive) It returns the group of elements that are less than or
equal to(if, inclusive is true) the specified element.
NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range.
SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.
SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or
equal to the specified element.
NavigableSet tailSet(E fromElement, boolean inclusive) It returns a set of elements that are greater than or
equal to (if, inclusive is true) the specified element.
boolean contains(Object o) It returns true if this set contains the specified element.
boolean remove(Object o) It is used to remove the specified element from this set
if it is present.
void clear() It is used to remove all of the elements from this set.
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and value pair, where
keys should be unique. If you try to insert the duplicate key, it will replace the element of the
corresponding key. It is easy to perform operations using the key index like updation, deletion, etc.
HashMap class is found in the [Link] package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the
null elements as well, but there should be only one null key. Since Java 5, it is denoted
as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and
implements the Map interface.
Points to remember
o Java HashMap contains values based on the key.
o Java HashMap contains only unique keys.
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Syntax:
Hashmap<Key Datatype, Value Datatype> Hashmap_Var = new Hashmap<Key Datatype, Value Datatype>();
HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements of the given
extends V> m) Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer
value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of the hash map
loadFactor) by using its arguments.
void clear() It is used to remove all of the mappings from this map.
Object clone() It is used to return a shallow copy of this HashMap instance: the
keys and values themselves are not cloned.
Set keySet() It is used to return a set view of the keys contained in this map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the map
only if it is not already specified.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys
from the map.
V compute(K key, BiFunction<? super K,? It is used to compute a mapping for the specified key and its
super V,? extends V> remappingFunction) current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super It is used to compute its value using the given mapping function,
K,? extends V> mappingFunction) if the specified key is not already associated with a value (or is
mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given the key and its
super K,? super V,? extends V> current mapped value if the value for the specified key is present
remappingFunction) and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the value exists
within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key exists
within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super It performs the given action for each entry in the map until all
V> action) entries have been processed or the action throws an exception.
V get(Object key) This method returns the object that contains the value associated
with the key.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or
defaultValue if the map contains no mapping for the key.
boolean isEmpty() This method returns true if the map is empty; returns false if it
contains at least one key.
V merge(K key, V value, BiFunction<? super If the specified key is not already associated with a value or is
V,? super V,? extends V> associated with null, associates it with the given non-null value.
remappingFunction)
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified key.
newValue)
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking the given
super V,? extends V> function) function on that entry until all entries have been processed or the
function throws an exception.
Collection<V> values() It returns a collection view of the values contained in the map.
int size() This method returns the number of entries in the map.
import [Link].*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
[Link](1,"Mango"); //Put elements in Map
[Link](2,"Apple");
[Link](3,"Banana"); Output:
Iterating Hashmap...
[Link](4,"Grapes");
1 Mango
2 Apple
[Link]("Iterating Hashmap..."); 3 Banana
for([Link] m : [Link]()){ 4 Grapes
[Link]([Link]()+" "+[Link]());
}
} }
John Selva Raj
Mohan Babu University
Points to remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is identified by
calling the hashcode() method. A Hashtable contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Syntax:
Hashtable<Key Datatype, Value Datatype> Hashtable_Var = new Hashtable<Key Datatype, Value Datatype>();
Hashtable() It creates an empty hashtable having the initial default capacity and load factor.
Hashtable(int It accepts an integer parameter and creates a hash table that contains a specified initial
capacity) capacity.
V compute(K key, BiFunction<? super K,? It is used to compute a mapping for the specified key and its
John Selva Raj
Mohan Babu University
super V,? extends V> remappingFunction) current mapped value (or null if there is no current mapping).
V computeIfAbsent(K key, Function<? super It is used to compute its value using the given mapping function,
K,? extends V> mappingFunction) if the specified key is not already associated with a value (or is
mapped to null), and enters it into this map unless null.
V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given the key and its
super K,? super V,? extends V> current mapped value if the value for the specified key is present
remappingFunction) and non-null.
Set<[Link]<K,V>> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? super It performs the given action for each entry in the map until all
V> action) entries have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped, or
defaultValue if the map contains no mapping for the key.
int hashCode() It returns the hash code value for the Map
Set<K> keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction<? super If the specified key is not already associated with a value or is
V,? super V,? extends V> associated with null, associates it with the given non-null value.
remappingFunction)
V put(K key, V value) It inserts the specified value with the specified key in the hash
table.
void putAll(Map<? extends K,? extends V> It is used to copy all the key-value pair from map to hashtable.
t))
V putIfAbsent(K key, V value) If the specified key is not already associated with a value (or is
mapped to null) associates it with the given value and returns
null, else returns the current value.
boolean remove(Object key, Object value) It removes the specified values with the associated specified keys
from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified key.
newValue)
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking the given
super V,? extends V> function) function on that entry until all entries have been processed or
the function throws an exception.
Collection values() It returns a collection view of the values contained in the map.
boolean contains(Object value) This method returns true if some value equal to the value exists
within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value exists
within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exists within
the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns false
if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and rehashes all
of its keys.
V get(Object key) This method returns the object that contains the value associated
with the key.
V remove(Object key) It is used to remove the key and its value. This method returns
the value associated with the key.
int size() This method returns the number of entries in the hash table.
Output:
[Link](100,"Amit"); 103 Rahul
102 Ravi
[Link](102,"Ravi"); 101 Vijay
[Link](101,"Vijay"); 100 Amit
[Link](103,"Rahul");
for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
}
} }
John Selva Raj
Mohan Babu University
Iterator in Java
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced in order to
iterate over a collection of Java object components entirety one by one. It is free to use in the Java
programming language since the Java 1.2 Collection framework. It belongs to [Link] package.
Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool available to
traverse through the elements of the Collection object. The oldest Iterator in the Java programming
language is the Enumerator predated Iterator. Java Iterator interface succeeds the enumerator iterator
that was practiced in the beginning to traverse over some accessible collections like the ArrayLists.
The Java Iterator is also known as the universal cursor of Java as it is appropriate for all the classes of
the Collection framework. The Java Iterator also helps in the operations like READ and REMOVE. When
we compare the Java Iterator interface with the enumeration iterator interface, we can say that the
names of the methods available in Java Iterator are more precise and straightforward to use.
o The user can apply these iterators to any of the classes of the Collection framework.
o In Java Iterator, we can use both of the read and remove operations.
o If a user is working with a for loop, they cannot modernize(add/remove) the Collection, whereas, if they
use the Java Iterator, they can simply update the Collection.
o The Java Iterator is considered the Universal Cursor for the Collection API.
o The method names in the Java Iterator are very easy and are very simple to use.
o The Java Iterator only preserves the iteration in the forward direction. In simple words, the Java Iterator is a
uni-directional Iterator.
o The replacement and extension of a new component are not approved by the Java Iterator.
o In CRUD Operations, the Java Iterator does not hold the various operations like CREATE and UPDATE.
o In comparison with the Spliterator, Java Iterator does not support traversing elements in the parallel
pattern which implies that Java Iterator supports only Sequential iteration.
o In comparison with the Spliterator, Java Iterator does not support more reliable execution to traverse the
bulk volume of data.
If the user modifies the underlying collection while traversing over an Iterator leading to that collection,
then the Iterator will typically acknowledge it and will throw an exception in the next time when the user
will attempt to get the next component from the Iterator.
o hasNext()
o next()
o remove()
o forEachRemaining()
The forEachRemaining() method was added in the Java 8. Let's discuss each method in detail.
o boolean hasNext(): The method does not accept any parameter. It returns true if there are more elements
left in the iteration. If there are no more elements left, then it will return false.
If there are no more elements left in the iteration, then there is no need to call the next() method. In
simple words, we can say that the method is used to determine whether the next() method is to be called
or not.
o E next(): It is similar to hasNext() method. It also does not accept any parameter. It returns E, i.e., the next
element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it
throws the NoSuchElementException.
o default void remove(): This method also does not require any parameters. There is no return type of this
method. The main function of this method is to remove the last element returned by the iterator
traversing through the underlying collection. The remove () method can be requested hardly once per the
next () method call. If the iterator does not support the remove operation, then it throws the
UnSupportedOperationException. It also throws the IllegalStateException if the next method is not yet
called.
o default void forEachRemaining(Consumer action): It is the only method of Java Iterator that takes a
parameter. It accepts action as a parameter. Action is nothing but that is to be performed. There is no
return type of the method. This method performs the particularized operation on all of the left
components of the collection until all the components are consumed or the action throws an exception.
Exceptions thrown by action are delivered to the caller. If the action is null, then it throws a
NullPointerException.
[Link]
import [Link].*;
import [Link].*;
[Link]("Delhi");
[Link]("Mumbai");
[Link]("Kolkata");
[Link]("Chandigarh");
[Link]("Noida");
while ([Link]())
[Link]([Link]() + " ");
[Link]();
}
}
John Selva Raj
Mohan Babu University
Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida
Points to Remember
o The Java Iterator is an interface added in the Java Programming language in the Java 1.2 Collection
framework. It belongs to [Link] package.
o It is one of the Java Cursors that are practiced to traverse the objects of the collection framework.
o The Java Iterator is used to iterate the components of the collection object one by one.
o The Java Iterator is also known as the Universal cursor of Java as it is appropriate for all the classes of the
Collection framework.
o The Java Iterator also supports the operations like READ and REMOVE.
o The methods names of the Iterator class are very simple and easy to use compared to the method names
of Enumeration Iterator.