0% found this document useful (0 votes)
7 views99 pages

Module 2

CLOUD COMPUTING

Uploaded by

Addds Muhammmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views99 pages

Module 2

CLOUD COMPUTING

Uploaded by

Addds Muhammmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 99

Module 3

The collections and Framework


Collections
• Any group of individual objects that are represented as a single unit is
known as a Java Collection of Objects.
Framework
• A framework provides a ready-made structure of classes and interfaces for
building software applications efficiently.
Collection framework
• The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It enhances code efficiency and readability
by offering various data structures, including arrays, linked lists, trees, and
hash tables to different programming needs.
• It has:
1.Interfaces and its implementations, i.e., classes
2.Algorithm
The Collection Framework Hierarchy
Collection Interface

• The Collection interface in Java is a core member of the Java


Collections Framework located in the java.util package.
• It is one of the root interfaces of the Java Collection Hierarchy.
The Collection interface is not directly implemented by any class.
• Instead, it is implemented indirectly through its sub-interfaces like
List, Queue, and Set.
• For Example, the ArrayList class implements the List interface, a sub-
interface of the Collection interface.
Hierarchy of Collection Interface
• The Collection interface is part of a hierarchy that extends Iterable, means
collections can be traversed.
• The hierarchy also includes several key sub-interfaces:
• Iterable

• Collection
• List
• Set
• Queue
• Deque
• SortedSet
• NavigableSet
1. List
• The List interface represents an ordered collection that allows
duplicates. It is implemented by classes like ArrayList, LinkedList,
and Vector. Lists allow elements to be accessed by their index position.
public interface List<E> extends Collection<E>
2. Set
• A set is an unordered collection of objects in which duplicate values
cannot be stored. This set interface is implemented by various classes
like HashSet, TreeSet, LinkedHashSet, etc.
• public interface Set<E> extends Collection<E>
3. SortedSet
• This interface is very similar to the set interface. The only difference is
that this interface has extra methods that maintain the ordering of the
elements. The sorted set interface extends the set interface and is used
to handle the data which needs to be sorted. The class which
implements this interface is TreeSet.
public interface SortedSet<E> extends Set<E>
4. Queue
• The Queue interface represents a collection that follows FIFO (First-
In-First-Out) order. It is implemented by classes like PriorityQueue,
Deque, ArrayDeque, etc.
public interface Queue<E> extends Collection<E>
• 5. Deque

• The Deque interface extends Queue and allows elements to be added


or removed from both ends of the queue. It is implemented by
ArrayDeque and LinkedList.
• public interface Deque<E> extends Queue<E>
• 6. NavigableSet

• The NavigableSet interface extends SortedSet and provides additional


methods for navigation such as finding the closest element.
• public interface NavigableSet<E> extends SortedSet<E>
import java.util.*;
public class collections
{
public static void main(String[] args)
{
Collection<String> c = new ArrayList<>();
c.add("Apple");
c.add("Banana");
c.add("Orange");
System.out.println("Collection: " + c);
}
}
Lists
• The List Interface in Java extends the Collection Interface and is a part of
java.util package. It is used to store the ordered collections of elements. So
in a Java List, you can organize and manage the data sequentially.
• Maintained the order of elements in which they are added.
• Allows the duplicate elements.

• The implementation classes of the List interface are ArrayList, LinkedList,


Stack, and Vector.

• Can add Null values that depend on the implementation.


• ArrayList
• Java ArrayList is a part of collections framework and it is a class of
java.util package.
• It provides us with dynamic arrays in Java.
• The main advantage of ArrayList is, unlike normal arrays, we don’t
need to mention the size when creating ArrayList.
• It automatically adjusts its capacity as elements are added or removed.
Methods of the ArrayList Class
1. boolean addAll(Collection c)
• This version appends all elements of the specified collection to the end of the
ArrayList.
• Parameters: c: The collection containing elements to be added to the
ArrayList.

• Return Value: true: If the elements were successfully added.

2. boolean addAll(int index, Collection c)

• This version inserts all elements from the specified collection into the
ArrayList at the specified index. It shifts the current elements and subsequent
elements to the right.
import java.util.ArrayList;
public class add
{
public static void main(String[] args)
{
ArrayList<String> a = new ArrayList<>();
a.add("Java");
a.add("C++");
a.add("Python");
a.add("web");
ArrayList<String> b = new ArrayList<>();
b.add("DMS");
b.add("AI");
b.add("WEB");
a.addAll(b);
System.out.println(" " + a);
a.addAll(2,b);
System.out.println(" " + a);
}} output
C:\raghu.java>java add
[Java, C++, Python, web, DMS, AI, WEB]
[Java, C++, DMS, AI, WEB, Python, web, DMS, AI, WEB]
3. get(int index):
• It is used to fetch the element from the particular position of the list.
4.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.
5. 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.
6. remove(int index):
• It is used to remove the element present at the specified position in the list.
7.removeAll(Collection<?> c):
• It is used to remove all the elements from the list.
Example
import java.util.*;
public class ListExample1
{
public static void main(String args[])
{
List<String> a=new ArrayList<String>();
a.add("Mango");
a.add("Apple");
a.add("Banana");
a.add("Grapes");
a.add("Mango");
System.out.println("Element at Index 1: "+ a.get(2));
a.remove("Banana");
System.out.println("List After Removing Element: " + a);
int i = a.indexOf("Mango");
System.out.println("First Occurrence of Mango is at Index: "+i);
int b = a.lastIndexOf("Mango");
System.out.println("Last Occurrence of Mango is at Index: "+b);
a.removeAll(a);
System.out.println("List After Removing Element: " + a);
}} output
Element at Index 1: Banana
List After Removing Element: [Mango, Apple, Grapes, Mango]
First Occurrence of Mango is at Index: 0
Last Occurrence of Mango is at Index: 3
List After Removing Element: []
8. void removeRange(int fromIndex, int toIndex):
It is used to remove all the elements lies within the given range.
9. void retainAll(Collection<?> c):
The retainAll () method of Java ArrayList class keeps only elements in the
original list that are contained in the specified collection. In other words, it
replaces the original list with the specified list.
10. set(int index, E element):
It is used to replace the specified element in the list, present at the specified
position.
11. int size():
It is used to return the number of elements present in the list.
12. iterator():Returns an iterator over the elements in this collection.
Example
import java.util.ArrayList;
public class Demoretain
{
public static void main(String[] args)
{
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.add("Toyota");
System.out.println("Element of cars: " + cars);
ArrayList<String> valid = new ArrayList<String>();
valid.add("Volvo");
valid.add("Ford");
valid.add("Mazda");
System.out.println("Element of valid: " + valid);
cars.retainAll(valid);
System.out.println("elements of cars after retain: " +cars);
}} output

Element of cars: [Volvo, BMW, Ford, Mazda, Toyota]


Element of valid: [Volvo, Ford, Mazda]
elements of cars after retain: [Volvo, Ford, Mazda]
Example
class removeall
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<>();
al.add("PUC");
al.add("MBA");
al.add(1, "MCA");
al.add(3, "BE");
System.out.println("After Adding element at index 1 : "+ al);
al.remove(0);
System.out.println("Element removed from index 0 : "+ al);
al.set(0, "RAJ");
System.out.println("List after updation of value : "+al);
System.out.println("size of the list : "+al.size());
}
} output
After Adding element at index 1 : [PUC, MCA, MBA, BE]
Element removed from index 0 : [MCA, MBA, BE]
List after updation of value : [RAJ, MBA, BE]
size of the list : 3
iterator() Example:
import java.util.*;
public class iterator
{
public static void main(String[] args)
{
Collection<String> l = new LinkedList<>();
l.add("RNSIT");
l.add("MCA");
l.add("MBA");
System.out.println("The list is:" + l);
Iterator<String> it = l.iterator();
System.out.println("\nThe iterator values of list are: ");
while (it.hasNext())
{
System.out.println(it.next() + " ");
}
}
} output
The iterator values of list are:
RNSIT
MCA
MBA
RemoveRange Example:
class Custom extends ArrayList<Integer>
{
public void removeRangeList(int s, int e)
{
removeRange(s, e);
}
}
public class RemoveRange
{
public static void main(String[] args)
{
Custom n = new Custom();
n.add(5);
n.add(7);
n.add(11);
n.add(13);
n.add(17);
System.out.println("" + n);
n.removeRangeList(1, 4);
System.out.println("" + n);
}} output
[5, 7, 11, 13, 17]
[5, 17]
Vectors
• 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 java.util package and implements the List interface, so
we can use all the methods of List interface here.
Java Vector Constructors
Constructor Description

It constructs an empty vector with the


vector()
default size as 10.

It constructs an empty vector with the


vector(int initialCapacity) specified initial capacity and with its
capacity increment equal to zero.
It constructs an empty vector with the
vector(int initialCapacity, int
specified initial capacity and capacity
capacityIncrement)
increment.

It constructs a vector that contains the


Vector( Collection<? extends E> c)
elements of a collection c.
Java Vector Methods
Method Description
It is used to append the specified component to the end of this vector. It
addElement()
increases the vector size by one.
clear() It is used to delete all of the elements from this vector.
clone() It returns a clone of this vector.
copyInto() It is used to copy the components of the vector into the specified array.
elementAt() It is used to get the component at the specified index.
hashCode() It is used to get the hash code value of a vector.
It is used to insert the specified object as a component in the given
insertElementAt()
vector at the specified index.
removeElementAt() It is used to delete the component at the specified index.
It is used to set the size of the given vector.
setSize()
It is used to sort the list according to the order induced by the
sort() specified Comparator.
It is used to replace each element of the list with the result of
replaceAll()
applying the operator to that element.
isEmpty() It is used to check if this vector has no components.
It is used to compare the specified object with the vector for
equals()
equality.
contains() It returns true if the vector contains the specified element.
It returns true if the vector contains all of the elements in the
containsAll()
specified collection.
Clone example: Cloning in Java is the process of creating a copy of an existing object.
import java.util.Vector;
public class Clone
{
public static void main(String arg[])
{
Vector<String> vc = new Vector<String>();
vc.add("Tiger");
vc.add("Deer");
System.out.println("Original vector: "+vc);
System.out.println("Cloned vector: "+vc.clone());
} } output
Original vector: [Tiger, Deer]
Cloned vector: [Tiger, Deer]
Copyinto example:
import java.util.Vector;
public class CopyInto
{
public static void main(String arg[])
{
Vector<Integer> vec = new Vector<>();
vec.add(1);
vec.add(2);
vec.add(3);
Integer[] arr = new Integer[5];
vec.copyInto(arr);
System.out.println("Elements in an array are: ");
for(Integer num : arr)
{
System.out.println(num);
}
}
} output
Elements in an array are:
1
2
3
null
null
hashCode() example:
import java.util.*;
public class HashCode
{
public static void main(String arg[])
{
Vector < String > colors = new Vector< String >();
colors.add("White");
colors.add("Green");
System.out.println("Color elements in vector: " +colors);
System.out.println("HashCode: " +colors.hashCode());
}
} output
Color elements in vector: [White, Green]
HashCode: -1635874885
Example
import java.util.*;
public class VectorExample
{
public static void main(String arg[])
{
Vector<Integer> vec = new Vector<>();
vec.add(10);
vec.add(20);
vec.add(30);
vec.add(40);
vec.add(50);
vec.add(10);
vec.add(10);
System.out.println("Vector element before removal: " +vec);
vec.removeElementAt(2);
System.out.println("Vector element after removal: " +vec);
vec.insertElementAt(32, 1);
System.out.println("after inserted: " +vec);
System.out.println("Existence: "+vec.contains(33));
List<Integer> list = new Vector<>();
list.add(20);
list.add(30);
System.out.println("Does vector contains all list elements?: "+vec.containsAll(list));
Collections.replaceAll(vec, 10, 2);
System.out.println("New vector elements: " + vec);
vec.clear();
System.out.println("Size of Vector after clear() method: "+vec.size());

}
} output
Vector element before removal: [10, 20, 30, 40, 50, 10, 10]
Vector element after removal: [10, 20, 40, 50, 10, 10]
after inserted: [10, 32, 20, 40, 50, 10, 10]
Existence: false
Does vector contains all list elements?: false
New vector elements: [2, 32, 20, 40, 50, 2, 2]
Size of Vector after clear() method: 0
LinkedList

• Linked List is a part of the Collection framework present in java.util


package.
• This class is an implementation of the LinkedList data structure which
is a linear data structure where the elements are not stored in
contiguous locations and every element is a separate object with a data
part and address part.
Method Description

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.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

boolean
It is used to remove the first occurrence of the specified element in a list (when
removeFirstOccurrence(
traversing the list from head to tail).
Object o)

E removeLast() It removes and returns the last element from a list.

E set(int index, E It replaces the element at the specified position in a list with the specified
element) element.
boolean
It removes the last occurrence of the specified element in a list (when traversing
removeLastOccurrence(
the list from head to tail).
Object o)
Example
import java.util.LinkedList;
public class linkedlist
{
public static void main(String args[])
{
LinkedList<String> l = new LinkedList<>();
l.add("delhi");
l.add("bangalore");
l.add("delhi");
l.add("hyderabad");
l.add("bangalore");
System.out.println("Before adding new elements: " + l);
l.addFirst("Platform");
System.out.println("After adding new elements: " + l);
l.addLast("Coding");
System.out.println("The new LinkedList is: " + l);
System.out.println("Element : " + l.get(1));
System.out.println("Element at 1st index is : "+ l.getFirst());
System.out.println("Element at 1st index is : "+ l.getLast());
System.out.println("First Occurence of B is removed: " +
l.removeFirstOccurrence("delhi"));
System.out.println("First Occurence of B is removed: " +
l.removeLastOccurrence("bangalore"));
System.out.println("The new LinkedList is: " + l);
}
} output

Before adding new elements: [delhi, bangalore, delhi, hyderabad, bangalore]


After adding new elements: [Platform, delhi, bangalore, delhi, hyderabad, bangalore]
The new LinkedList is: [Platform, delhi, bangalore, delhi, hyderabad, bangalore,
Coding]
Element : delhi
Element at 1st index is : Platform
Element at 1st index is : Coding
First Occurence of B is removed: true
First Occurence of B is removed: true
The new LinkedList is: [Platform, bangalore, delhi, hyderabad, Coding]
Stack

• Java Collection framework provides a Stack class that models and


implements a Stack data structure.
• The class is based on the basic principle of LIFO(last-in-first-
out).
• In addition to the basic push and pop operations, the class
provides three more functions of empty, search, and peek.
• The Stack class extends Vector and provides additional
functionality specifically for stack operations, such as push, pop,
peek, empty, and search.
• The Stack class can indeed be referred to as a subclass of Vector,
inheriting its methods and properties.
peek() Method
• The peek() method returns the top element of the stack without removing it
search() Method
• The method searches the object in the stack from the top.
• It returns the object location from the top of the stack. If it returns -1, it
means that the object is not on the stack.
empty() Method
• The empty() method of the Stack class check the stack is empty or not.
• The method returns true if the stack is empty, else returns false.
• pop() Method
• The method removes an object at the top of the stack and returns the same
object
• Let's push 20, 13, 89, 90, 11, 45, 18, respectively into the stack.
Example
import java.util.*;
public class StackExample
{
public static void main(String[] args)
{
Stack<Integer> s = new Stack<>();
s.push(12);
s.push(24);
s.push(31);
s.push(42);
System.out.println(s);
System.out.println("Element at " + s.peek());
System.out.println("Element at " + s.search(42));
System.out.println("Element at " + s.empty());
while(!s.isEmpty())
{
System.out.println(s.pop());
}
}
} output
C:\raghu.java>java StackExample
[12, 24, 31, 42]
Element at 42
Element at 1
Element at false
42
31
24
12
Queue
• The Queue Interface is present in java.util package and extends the
Collection interface.
• It stores and processes the data in FIFO(First In First Out) order.
• It is an ordered list of objects limited to inserting elements at the end of the
list and deleting elements from the start of the list.
• Here are some of the most commonly used methods:
• add(element): Adds an element to the rear of the queue. If the queue is full,
it throws an exception.

• offer(element): Adds an element to the rear of the queue. If the queue is full,
it returns false.
• remove(): Removes and returns the element at the front of the queue.
If the queue is empty, it throws an exception.
• poll(): Removes and returns the element at the front of the queue. If
the queue is empty, it returns null.
• peek(): Returns the element at the front of the queue without
removing it. If the queue is empty, it returns null.

Example
import java.util.*;
public class queue
{
public static void main(String args[])
{
Queue<String> pq = new PriorityQueue<>();
pq.add("car");
pq.add("bus");
pq.add("van");
pq.add("vahicle");
pq.add("mca");
System.out.println("Initial Queue " + pq);
pq.remove("bus");
System.out.println("After Remove " + pq);
pq.offer("rnsit");
System.out.println("After offer " + pq);
System.out.println("Poll Method " + pq.poll());
System.out.println("Final Queue " + pq);
System.out.println(pq.peek());
}
} output
Initial Queue [bus, car, van, vahicle, mca]
After Remove [car, mca, van, vahicle]
After offer [car, mca, van, vahicle, rnsit]
Poll Method car
Final Queue [mca, rnsit, van, vahicle]
Set

• The Set Interface is present in java.util package and extends


the Collection interface.
• It is an unordered collection of objects in which duplicate values
cannot be stored.
• It is an interface that implements the mathematical set.
• This interface adds a feature that restricts the insertion of the
duplicate elements.
• There are two interfaces that extend the set implementation
namely SortedSet and NavigableSet.
Method Description
add(element) This method is used to add a specific element to the set.

This method is used to append all of the elements from the mentioned
addAll(collection)
collection to the existing set.
This method is used to remove all the elements from the set but not
clear()
delete the set.
This method is used to check whether a specific element is present in
contains(element)
the Set or not.
This method is used to check whether the set contains all the elements
containsAll(collection
present in the given collection or not.
This method is used to get the hashCode value for this instance of the
hashCode()
Set.

isEmpty() This method is used to check whether the set is empty or not.

This method is used to remove the given element from the set. This
remove(element) method returns True if the specified element is present in the Set
otherwise it returns False.
Method Description
This method is used to remove all the elements from the
removeAll(collection) collection which are present in the set. This method returns
true if this set changed as a result of the call.
This method is used to retain all the elements from the set
retainAll(collection) which are mentioned in the given collection. This method
returns true if this set changed as a result of the call.
This method is used to get the size of the set. This returns an
size()
integer value which signifies the number of elements.
import java.util.*;
public class set
{
public static void main(String[] args)
{
Set<String> h = new HashSet<String>();

h.add("raghu");
h.add("prasad");
h.add("raghu");
h.add("kiran");
h.add("vijay");
System.out.println(h);
} output
} [raghu, kiran, vijay, prasad]
Example
import java.util.*;
public class setprogram
{
public static void main(String[] args)
{
Set<String> h = new HashSet<String>();
h.add("raghu");
h.add("prasad");
h.add("raghu");
h.add("kiran");
h.add("vijay");
System.out.println(h);
Set<String> k = new HashSet<String>();
k.add("murali");
k.add("arun");
k.add("ajay");
System.out.println(k);
h.addAll(k);
System.out.println(h);
System.out.println("Does the Set contains raghu: " +
h.contains("raghu"));
System.out.println("Does h contains newData: "+
h.containsAll(k));
System.out.println("\nThe hash code value of set is:"+
h.hashCode());
System.out.println("size of the data is : " + h.size());
System.out.println("\nIs data empty?: "+ h.isEmpty());
h.remove("vijay");
System.out.println("data after removing elements: " + h);

h.retainAll(k);
System.out.println("data after retaining newdata elements : " + h);
h.clear();
System.out.println("The final set: " + h);
h.removeAll(k);
System.out.println("data after removing Newdata elements : " + h);
}
}
Output
[raghu, kiran, vijay, prasad]
[arun, murali, ajay]
[arun, murali, raghu, ajay, kiran, vijay, prasad]
Does the Set contains raghu: true
Does h contains newData: true
The hash code value of set is:-1714525493
size of the data is : 7
Is data empty?: false
data after removing elements: [arun, murali, raghu, ajay, kiran, prasad]
data after retaining newdata elements : [arun, murali, ajay]
The final set: []
data after removing Newdata elements : []
SortedSet

• The SortedSet interface is present in java.util package extends the


Set interface present in the collection framework.
• It is an interface that implements the mathematical set.
• This interface contains the methods inherited from the Set interface
and adds a feature that stores all the elements in this interface to be
stored in a sorted manner.
• Automatic Sorting: Elements are stored in ascending order by
default.
• Unique Elements: Ensures that no duplicate elements are present.
• Null Handling: Typically null elements are not allowed.
Method Description
first() Returns the first element from the current set.
Returns a view of the portion of the given set
headSet(E toElement) whose elements are strictly less than the
toElement.
Returns the reverse order view of the mapping
last()
which present in the map.
Returns a view of the map whose keys are
tailSet(E fromElement)
strictly less than the toKey.
Returns a key-value mapping which is
subSet(E fromElement, associated with the greatest key which is less
E toElement) than or equal to the given key. Also, returns null
if the map is empty.
import java.util.*;
public class sortedset
{
public static void main(String[] args)
{
SortedSet<Integer> sortedSet = new TreeSet<>();
sortedSet.add(5);
sortedSet.add(3);
sortedSet.add(8);
sortedSet.add(2);
sortedSet.add(10);
System.out.println("Sorted Set: " + sortedSet);
System.out.println("First element: " + sortedSet.first());
System.out.println("Last element: " + sortedSet.last());
SortedSet<Integer> headSet = sortedSet.headSet(5);
System.out.println("Head set (less than 5): " + headSet);
SortedSet<Integer> tailSet = sortedSet.tailSet(5);
System.out.println("Tail set (greater than or equal to 5): " +
tailSet);
SortedSet<Integer> subSet = sortedSet.subSet(3, 8);
System.out.println("Subset (from 3 inclusive to 8 exclusive): " + subSet);

}
}
Output
Sorted Set: [2, 3, 5, 8, 10]
First element: 2
Last element: 10
Head set (less than 5): [2, 3]
Tail set (greater than or equal to 5): [5, 8, 10]
Subset (from 3 inclusive to 8 exclusive): [3, 5]
What is the difference between List and Set in Java

List Set
The List is an indexed sequence. The Set is a non-indexed sequence.
The set doesn’t allow duplicate
The list allows duplicate elements
elements.
Elements by their position can be Position access to elements is not
accessed. allowed.
Multiple null elements can be stored. Null elements can store only once.
List implementations are ArrayList, Set implementations are HashSet,
LinkedList, Vector, Stack LinkedHashSet.
Map Interface

• The map interface in Java is a structure that holds a set of key-


value pairs where each key is unique and points to one value only.
• It is a component of the java.util package and is being widely used
in Java programming to structure and get data in an ordered manner.
• A Map is useful if you have to search, update or delete elements on
the basis of a key.
• A Map doesn't allow duplicate keys, but you can have duplicate
values.
Class Description

HashMap is the implementation of Map, but it doesn't


HashMap
maintain any order.

LinkedHashMap is the implementation of Map. It inherits


LinkedHas
hMap HashMap class. It maintains insertion order.

TreeMap is the implementation of Map and SortedMap.


TreeMap
It maintains ascending order.
Method Description
getKey() It is used to obtain a key.
V getValue() It is used to obtain value.
int hashCode() It is used to obtain hashCode.
It is used to replace the value corresponding to this entry with
V setValue(V value)
the specified value.
It is used to compare the specified object with the other
boolean equals(Object o)
existing objects.
This method is used in Java Map Interface to clear and remove
clear() all of the 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
This method is used in Map Interface to check whether a
particular value is being mapped by a single or more than one
containsValue(Object)
key in the Map. It takes the value as a parameter and returns
True if that value is mapped by any of the keys in the map.
Method Description

This method is used to retrieve or fetch the value mapped by a


get(Object) particular key mentioned in the parameter. It returns NULL when
the map contains no such mapping for the key.
This method is used to check if a map is having any entry for key
isEmpty()
and value pairs. If no mapping exists, then this returns true.
This method is used in Map Interface to remove the mapping for a
remove(Object)
key from this map if it is present in the map.
This method is used to return the number of key/value pairs
size()
available in the map.
This method is used in Map Interface in Java to create a set out of
the same elements contained in the map. It basically returns a set
entrySet()
view of the map or we can create a new set and store the map
elements into them.
import java.util.HashMap;
import java.util.Map;
public class Map10
{
public static void main(String args[])
{
Map<String, String> hm= new HashMap<String, String>();
hm.put("a", "raghu");
hm.put("b", "prasad");
hm.put("c", "shiva");
hm.put("d", "Kiran");
for (Map.Entry<String, String> me :hm.entrySet())
{
System.out.println (me.getKey() + ":" + me.getValue());
}
}
} output
C:\raghu.java>java Map10
d:Kiran
b:prasad
c:shiva
a:raghu
Sorted Map
• SortedMap is an interface in the collection framework that is a part of
java.util package and extends the Map interface.
• It represents a map that maintains its keys in a sorted order.
• The keys in a SortedMap are sorted according to their natural ordering
or by a Comparator provided at the time of map creation.

Example
import java.util.SortedMap;
import java.util.TreeMap;
public class sortedmap
{
public static void main(String[] args)
{
SortedMap<String, Integer> s = new TreeMap<>();
s.put("A", 26);
s.put("C", 4);
s.put("B", 7);
System.out.println("SortedMap: " + s);
int ans = s.get("A");
System.out.println("Value of A: " + ans);
s.remove("B");
System.out.println(
"Updated SortedMap After removal:" + s);
}
}
Output
C:\raghu.java>java sortedmap
SortedMap: {A=26, B=7, C=4}
Value of A: 26
Updated SortedMap After removal:{A=26, C=4}
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 java.util package.

• Example: slide 72
TreeMap

• TreeMap is a part of the Java Collection Framework.


• It implements the Map and NavigableMap interface and extends the
AbstarctMap class.
• It stores key-value pairs in a sorted order based on the natural
ordering of keys or a custom.

• Example: slide 75
LinkedHashMap

• LinkedHashMap in Java implements the Map interface of the


Collections Framework.
• It stores key-value pairs while maintaining the insertion order of the
entries. It maintains the order in which elements are added.
• Stores unique key-value pairs.

• Maintains insertion order.

• Allows one null key and multiple null values.

• Fast performance for basic operations.


import java.util.*;
class linkedhashedmap
{
public static void main(String args[])
{
LinkedHashMap<Integer, String> lhm = new LinkedHashMap<Integer,
String>();
lhm.put(3, "bangalore");
lhm.put(2, "delhi");
lhm.put(1, "hyderabad");
System.out.println("" + lhm);
}
} output
{3=bangalore, 2=delhi, 1=hyderabad}
Collection algorithms in java

• The java collection framework defines several algorithms as static


methods that can be used with collections and map objects.
• All the collection algorithms in the java are defined in a class
called Collections which defined in the java.util package.
• All these algorithms are highly efficient and make coding very easy.
It is better to use them than trying to re-implement them.
• The collection framework has the following methods as algorithms.
Method Description
void sort(List list) Sorts the elements of the list as determined by their natural
ordering.
void reverse(List list) Reverses all the elements sequence in list.
void copy(List list1, List Copies the elements of list2 to list1.
list2)
void swap(List list, int idx1, Exchanges the elements in the list at the indices specified by
int idx2) idx1 and idx2.
int binarySearch(List list, Returns the position of value in the list (must be in the sorted
Object value) order), or -1 if value is not found.
nt indexOfSubList(List list, Returns the index of the first match of subList in the list, or -1
List subList) if no match is found.
int lastIndexOfSubList(List Returns the index of the last match of subList in the list, or -1 if
list, List subList) no match is found.
Object max(Collection c) Returns the largest element from the collection c as determined
by natural ordering.
Object min(Collection Returns the smallest element from the collection
c) c as determined by natural ordering.
void fill(List list, Object Assigns obj to each element of the list.
obj)
boolean replaceAll(List Replaces all occurrences of old with new in the list.
list, Object old, Object
new)
void shuffle(List list) Shuffles the elements in list.
import java.util.*;
public class CollectionAlgorithms
{
public static void main(String[] args)
{
ArrayList list = new ArrayList();
PriorityQueue queue = new PriorityQueue();
HashSet set = new HashSet();
HashMap map = new HashMap();
Random num = new Random();
for(int i = 0; i < 5; i++)
{
list.add(num.nextInt(100));
queue.add(num.nextInt(100));
set.add(num.nextInt(100));
map.put(i, num.nextInt(100));
}
System.out.println("List => " + list);
System.out.println("Queue => " + queue);
System.out.println("Set => " + set);
System.out.println("Map => " + map);
System.out.println("---------------------------------------");
Collections.sort(list);
System.out.println("List in ascending order => " + list);
System.out.println("Largest element in set => " +
Collections.max(set));
System.out.println("Smallest element in queue => " +
Collections.min(queue));
Collections.reverse(list);
System.out.println("List in reverse order => " + list);
Collections.shuffle(list);
System.out.println("List after shuffle => " + list);
}
}
Output
C:\raghu.java>java CollectionAlgorithms
List => [12, 69, 88, 17, 7]
Queue => [0, 25, 6, 74, 66]
Set => [51, 69, 54, 46, 13]
Map => {0=3, 1=27, 2=22, 3=26, 4=38}
---------------------------------------
List in ascending order => [7, 12, 17, 69, 88]
Largest element in set => 69
Smallest element in queue => 0
List in reverse order => [88, 69, 17, 12, 7]
List after shuffle => [69, 7, 12, 17, 88]
The legacy classes and interfaces in java
• The java.util package defines the following legacy classes:
• HashTable
• Stack
• Dictionary
• Properties
• Vector
• and the Enumeration interface
Hashtable Class
• The Hashtable class is similar to HashMap. It also contains the data into
key/value pairs.
• It doesn't allow to enter any null key and value because it is synchronized.
• Just like Vector, Hashtable also has the following four constructors.
Example
class hashtable
{
public static void main(String args[])
{
Hashtable<Integer,String> student = new Hashtable<Integer, String>();
student.put(new Integer(101), "Emma");
student.put(new Integer(102), "Adele");
student.put(new Integer(103), "Aria");
student.put(new Integer(104), "Ally");
Set dataset = student.entrySet();
Iterator iterate = dataset.iterator();
while(iterate.hasNext())
{
Map.Entry map=(Map.Entry)iterate.next();
System.out.println(map.getKey()+" "+map.getValue());
} } } output
104 Ally
103 Aria
102 Adele
101 Emma
Dictionary class

• Dictionary class in Java is an abstract class that represents a


collection of key-value pairs, where keys are unique and used to
access the values.
• It was part of the Java Collections Framework and it was
introduced in Java 1.0 but has been largely replaced by the Map
interface since Java 1.2.
• Stores key-value pairs, where keys are unique.Provides basic
operations like insert, retrieve, and remove key-value pairs.
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class diction
{
public static void main(String[] args)
{
Dictionary<String, Integer> d = new Hashtable<>();
d.put("A", 25);
d.put("B", 30);
d.put("C", 35);
System.out.println("Value of B: " + d.get("B"));
int oldValue = d.put("C", 40);
System.out.println("Old Value of C: " + oldValue);
d.remove("A");
Enumeration<String> k = d.keys();
while (k.hasMoreElements())
{
String key = k.nextElement();
System.out.println("Key: " + key + ", Value: " + d.get(key));
} }} output
Value of B: 30
Old Value of C: 35
Key: C, Value: 40
Key: B, Value: 30
Properties class

• 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 the properties
file and store data into the properties file.
• Moreover, it can be used to get the properties of a system.
Method Description
Public void load(InputStream method reads a property list (key and element pairs) from
is) the input byte stream
public String
It returns value based on the key.
getProperty(String key)
import java.util.*;
import java.io.*;
public class properties
{
public static void main(String[] args)throws Exception
{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
What are the uses of generic collections in Java

• The generic collections are introduced in Java 5 Version.


• The generic collections disable the type-casting and there is no use
of type-casting when it is used in generics.
• The generic collections are type-safe and checked at compile-time.
• These generic collections allow the datatypes to pass as parameters
to classes.
• The Compiler is responsible for checking the compatibility of the
types
Type safety
List list = new ArrayList(); // before generics
list.add(10);
list.add("100");
List<Integer> list1 = new ArrayList<Integer>(); // adding generics
list1.add(10);
list1.add("100"); // compile-time error.
Type Casting
• No need for type-casting while using generics.
List<String> list = new ArrayList<String>();
list.add("Adithya");
String str = list.get(0); // no need of type-casting
Compile-time
• The errors are checked at compile-time in generics.

List list = new ArrayList(); // before generics


list.add(10);
list.add("100");
List<Integer> list1 = new ArrayList<Integer>(); // adding generics
list1.add(10);
list1.add("100");// compile-time error

You might also like