Unit 3 Part II
Unit 3 Part II
For example, we
might want to display each element of a collection. The java provides an
interface Iterator that is available inside the java.util package to cycle through each
element of a collection.
🔔 The Iterator allows us to move only forward direction.
🔔 The Iterator does not support the replacement and addition of new elements.
We use the following steps to access a collection of elements using the Iterator.
Method Description
boolean hasNext( ) Returns true if the collection has the next element, otherwise, it return
Let's consider an example program to illustrate accessing elements of a collection via the
Iterator.
Example
import java.util.*;
}
}
Example
import java.util.*;
for(Object element:queue) {
System.out.print(element + ", ");
}
}
}
The For-Each alternative
Using for-each, we can access the elements of a collection. But for-each can only be used if
we don't want to modify the contents of a collection, and we don't want any reverse access.
Alternatively, we can use the Iterator to access or cycle through a collection of elements.
Let's consider an example program to illustrate The for-each alternative.
Example
import java.util.*;
while(collection.hasNext()) {
System.out.print(collection.next() + ", ");
}
}
}
Method Description
boolean hasNext( ) Returns true if the list collection has next element, otherwise it return
boolean hasPrevious( ) Returns true if the list collection has previous element, otherwise it re
int nextIndex( ) Returns the index of the next element. If there is no next element, ret
E previousIndex( ) Returns the index of the previous element. If there is no previous elem
Example
import java.util.*;
while(collection.hasNext()) {
System.out.print(collection.next() + ", ");
}
}
}
import java.util.HashMap;
3
import java.util.Map;
4
11
m.put("Geek1", 1);
13
m.put("Geek2", 2);
14
m.put("Geek3", 3);
15
16
}
18
Output
Map elements: {Geek3=3, Geek2=2, Geek1=1}
This method is used in Java Map Interface to clear and remove all of the
clear()
elements or mappings from a specified Map collection.
This method is used in Map Interface in Java to check whether a particular key
containsKey(Object) is being mapped into the Map or not. It takes the key element as a parameter
and returns True if that element is mapped in the map.
containsValue(Object) This method is used in Map Interface to check whether a particular value is
being mapped by a single or more than one key in the Map. It takes the value
Methods Action Performed
as a parameter and returns True if that value is mapped by any of the keys in
the map.
This method is used in Map Interface in Java to create a set out of the same
entrySet() elements contained in the map. It basically returns a set view of the map or
we can create a new set and store the map elements into them.
This method is used in Java Map Interface to check for equality between two
equals(Object) maps. It verifies whether the elements of one map passed as a parameter is
equal to the elements of this map or not.
This method is used to retrieve or fetch the value mapped by a particular key
get(Object) mentioned in the parameter. It returns NULL when the map contains no such
mapping for the key.
This method is used in Map Interface to generate a hashCode for the given
hashCode()
map containing keys and values.
This method is used to check if a map is having any entry for key and value
isEmpty()
pairs. If no mapping exists, then this returns true.
This method is used in Map Interface to return a Set view of the keys
keySet() contained in this map. The set is backed by the map, so changes to the map
are reflected in the set, and vice-versa.
This method is used in Java Map Interface to associate the specified value
put(Object, Object)
with the specified key in this map.
This method is used in Map Interface in Java to copy all of the mappings from
putAll(Map)
the specified map to this map.
This method is used in Map Interface to remove the mapping for a key from
remove(Object)
this map if it is present in the map.
Methods Action Performed
This method is used to return the number of key/value pairs available in the
size()
map.
This method is used in Java Map Interface to create a collection out of the
values() values of the map. It basically returns a Collection view of the values in the
HashMap.
getOrDefault(Object key, V Returns the value to which the specified key is mapped, or defaultValue if this
defaultValue) map contains no mapping for the key.
If the specified key is not already associated with a value (or is mapped to
putIfAbsent(K key, V value) null) associates it with the given value and returns null, else returns the
current associate value.
Example:
import java.util.*;
6
7
// Main class
8
class Geeks {
9
10
{
13
Map<String, Integer> hm
15
17
24
hm.entrySet()) {
27
28
System.out.print(me.getKey() + ":");
29
System.out.println(me.getValue());
30
}
31
}
32
Output
a:100
b:200
c:300
d:400
import java.util.*;
5
// Main class
7
{
12
13
m.put("Sweta", 10);
19
m.put("Amiya", 30);
20
m.put("Gudly", 20);
21
22
25
+ e.getValue());
27
}
28
Output
Amiya 30
Sweta 10
Gudly 20
2. LinkedHashMap
LinkedHashMap is just like HashMap with the additional feature of maintaining an
order of elements inserted into it. HashMap provided the advantage of quick
insertion, search, and deletion but it never maintained the track and order of
insertion which the LinkedHashMap provides where the elements can be accessed
in their insertion order. Let’s see how to create a map object using this class.
Example:
1
import java.util.*;
3
{
8
12
m.put("Sweta", 10);
15
m.put("Amiya", 30);
16
m.put("Gusly", 20);
17
18
21
+ e.getValue());
24
}
25
Output
Sweta 10
Amiya 30
Gusly 20
3. TreeMap
The TreeMap in Java is used to implement the Map interface
and NavigableMap along with the Abstract Class. The map is sorted according
to the natural ordering of its keys, or by a Comparator provided at map creation
time, depending on which constructor is used. This proves to be an efficient way of
sorting and storing the key-value pairs. The ordering maintained by the TreeMap
must be consistent with the equals() method if a custom comparator is not used.
Example:
import java.util.*;
5
6
// Main class
7
{
12
13
16
m.put("Sweta", 10);
19
m.put("Amiya", 30);
20
m.put("Gudly", 20);
21
22
25
}
28
Output
Amiya 30
Gudly 20
Sweta 10
import java.util.*;
4
class Geeks {
6
{
8
// Default Initialization of a
9
// Map
10
12
// Initialization of a Map
13
// using Generics
14
17
hm1.put(1, "Geeks");
19
hm1.put(2, "For");
20
hm1.put(3, "Geeks");
21
22
26
System.out.println(hm1);
27
System.out.println(hm2);
28
}
29
}
Output
{1=Geeks, 2=For, 3=Geeks}
{1=Geeks, 2=For, 3=Geeks}
2. Changing Element
After adding the elements if we wish to change the element, it can be done by
again adding the element with the put() method. The elements in the map are
indexed using the keys, the value of the key can be changed by simply inserting
the updated value for the key for which we want to change.
Example:
import java.util.*;
4
class Geeks {
6
{
8
// Initialization of a Map
10
// using Generics
11
19
21
23
}
25
Output
Initial Map: {1=Geeks, 2=Geeks, 3=Geeks}
Updated Map: {1=Geeks, 2=For, 3=Geeks}
3. Removing Elements
To remove an element from the Map, we can use the remove() method. This
method takes the key value and removes the mapping for a key from this map if it
is present in the map.
Example:
import java.util.*;
4
class Geeks {
6
{
9
10
// Initialization of a Map
11
// using Generics
12
15
21
System.out.println(hm1);
22
23
hm1.remove(new Integer(4));
24
25
System.out.println(hm1);
26
}
27
Output
{1=Geeks, 2=For, 3=Geeks, 4=For}
{1=Geeks, 2=For, 3=Geeks}
import java.util.*;
4
class Geeks {
6
{
8
9
// Initialization of a Map
10
// using Generics
11
14
19
22
25
}
27
}
28
Output
1 : Geeks
2 : For
3 : Geeks
import java.util.*;
4
class Geeks {
6
{
8
10
al.add(a[i]);
14
}
15
16
18
hm.putIfAbsent(al.get(i), Collections.frequency(
21
al, al.get(i)));
22
}
23
System.out.println(hm);
24
}
25
Output
{1=2, 2=1, 4=2, 41=1, 13=2, 31=2}
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called Enumeration
Enumeration interface
enumeration is complete.
Vector class
6.
8.
12.
Vector defines several legacy methods. Lets see some important legacy
methods defined by Vector class.
Method Description
void addElement(E element) adds element to the Vector
Example of Vector
import java.util.*;
ve.add(10);
ve.add(20);
ve.add(30);
ve.add(40);
ve.add(50);
ve.add(60);
Enumeration<Integer> en = ve.elements();
while(en.hasMoreElements())
System.out.println(en.nextElement());
10
20
30
40
50
60
Hashtable class
5.
7.
13.
Example of Hashtable
import java.util.*;
class HashTableDemo
Hashtable<String,Integer> ht = new
Hashtable<String,Integer>();
ht.put("a",new Integer(100));
ht.put("b",new Integer(200));
ht.put("c",new Integer(300));
ht.put("d",new Integer(400));
Set st = ht.entrySet();
Iterator itr=st.iterator();
while(itr.hasNext())
Map.Entry m=(Map.Entry)itr.next();
System.out.println(itr.getKey()+" "+itr.getValue());
}
a 100
b 200
c 300
d 400
Hashtable HashMap
Neither key nor values can be null Both key and values can be null
Order of table remain constant over does not guarantee that order of map
time. remain constant over time.
Stack class
4. If you want to put an object on the top of the stack, call push()
method. If you want to remove and return the top element, call pop()
method. An EmptyStackException is thrown if you call pop() method
when the invoking stack is empty.
You can use peek() method to return, but not remove, the top object. The
empty() method returns true if nothing is on the stack. The search()
method determines whether an object exists on the stack and returns the
number of pops that are required to bring it to the top of the stack.
Example of Stack
import java.util.*;
class StackDemo {
st.push(11);
st.push(22);
st.push(33);
st.push(44);
st.push(55);
Enumeration e1 = st.elements();
while(e1.hasMoreElements())
System.out.print(e1.nextElement()+" ");
st.pop();
st.pop();
Enumeration e2 = st.elements();
while(e2.hasMoreElements())
System.out.print(e2.nextElement()+" ");
11 22 33 44 55
11 22 33
Dictionary class
import java.util.Vector;
import java.util.Enumeration;
Enumeration months;
monthNames.add("February");
monthNames.add("March");
monthNames.add("April");
monthNames.add("May");
monthNames.add("June");
monthNames.add("July");
monthNames.add("August");
monthNames.add("September");
monthNames.add("October");
monthNames.add("November");
monthNames.add("December");
months = monthNames.elements();
while (months.hasMoreElements()) {
System.out.println(months.nextElement());
Output
January
February
March
April
May
June
July
August
September
October
November
December
Java Enumeration Interface With SequenceInputStream
Java
import java.io.*;
import java.util.*;
class GFG {
throws IOException
// files
FileInputStream fin
= new FileInputStream("file1.txt");
FileInputStream fin2
= new FileInputStream("file2.txt");
FileInputStream fin3
= new FileInputStream("file3.txt");
FileInputStream fin4
= new FileInputStream("file4.txt");
v.add(fin);
v.add(fin2);
v.add(fin3);
v.add(fin4);
// elements method
Enumeration e = v.elements();
SequenceInputStream bin
= new SequenceInputStream(e);
int i = 0;
System.out.print((char)i);
bin.close();
fin.close();
fin2.close();
import java.lang.reflect.Array;
if (!type.isArray()) {
size = Array.getLength(obj);
array = obj;
}
public object nextElements()
import java.io.*;
while (aenum.hasMoreElements()) {
System.out.println(aenum.nextElement());
E – type of elements
Modifier
And Type Method Explanation