Java Unit IV
Java Unit IV
UNIT-4
Collections in Java
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
• Interfaces
• Classes
• Algorithm
Interfaces: Interface in Java refers to the abstract data types. They allow Java collections
to be manipulated independently from the details of their representation. Also, they form
a hierarchy in object-oriented programming languages.
Classes: Classes in Java are the implementation of the collection interface. It basically
refers to the data structures that are used again and again.
Algorithm: Algorithm refers to the methods which are used to perform operations such
as searching and sorting, on objects that implement collection interfaces. Algorithms are
polymorphic in nature as the same method can be used to take many forms or you can
say perform different implementations of the Java collection interface.
• Reducing the effort required to write the code by providing useful data structures
and algorithms
• Java collections provide high-performance and high-quality data structures and
algorithms thereby increasing the speed and quality
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
1. Array list:
ArrayList is the implementation of List Interface where the elements can be
dynamically added or removed from the list. Also, the size of the list is
increased dynamically if the elements are added more than the initial size.
Syntax:
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Ram
Rahul
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
2.vector
Vectors : Vectors are similar to arrays, where the elements of the vector object can be
accessed via an index into the vector. Vector implements a dynamic array. Also, the
vector is not limited to a specific size, it can shrink or grow automatically whenever
required. It is similar to ArrayList, but with two differences :
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the collections
framework.
Example:
import java.io.*;
import java.util.*;
class vector1
{
public static void main(String[] args)
{
int n = 5;
Vector<Integer> v = new Vector<Integer>(n);
for (int i = 1; i <= n; i++)
v.add(i);
System.out.println(v);
v.remove(3);
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
System.out.println(v);
for (int i = 0; i < v.size(); i++)
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
4) static <T extends Object & Comparable<? max() It is used to get the
super T>> T maximum value of the
given collection, according
to the natural ordering of its
elements.
5) static <T extends Object & Comparable<? min() It is used to get the
super T>> T minimum value of the given
collection, according to the
natural ordering of its
elements.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
3. Stack Classes
The stack is a linear data structure that is used to store the collection of objects. It is based
on Last-In-First-Out (LIFO). Java collection framework provides many interfaces and
classes to store the collection of objects. One of them is the Stack class that provides
different operations such as push, pop, search, etc.
In this section, we will discuss the Java Stack class, its methods, and implement the
stack data structure in a Java program. But before moving to the Java Stack class have a
quick view of how the stack works.
The stack data structure has the two most important operations that are push and pop.
The push operation inserts an element into the stack and pop operation removes an
element from the top of the stack. Let's see how they work on stack.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Creating a Stack
Stack<type> stk = new Stack<>();
push(E item) E The method pushes (insert) an element onto the top of the stack.
pop() E The method removes an element from the top of the stack and
returns the same element as the value of that function.
peek() E The method looks at the top element of the stack without
removing it.
search(Object int The method searches the specified object and returns the position
o) of the object.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Example:
import java.util.Stack;
public class StackEmptyMethodExample
{
public static void main(String[] args)
{
//creating an instance of Stack class
Stack<Integer> stk= new Stack<>();
// checking stack is empty or not
boolean result = stk.empty();
System.out.println("Is the stack empty? " + result);
// pushing elements into stack
stk.push(78);
stk.push(113);
stk.push(90);
stk.push(120);
//prints elements of the stack
System.out.println("Elements in Stack: " + stk);
result = stk.empty();
System.out.println("Is the stack empty? " + result);
}
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
4. Linked List:
Linked List: Linked List is a sequence of links which contains items. Each link contains
a connection to another link.
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List: In a singly Linked list each node in this list stores the data of the node
and a pointer or reference to the next node in the list. Refer to the below image to get a
better understanding of single Linked list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node
and another to previous node. You can refer to the below image to get a better
understanding of doubly linked list.
Method Description
It is used to append the specified element to the end of the
boolean add( Object o)
vector.
boolean contains(Object
Returns true if this list contains the specified element.
o)
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
int lastIndexOf(Object Returns the index of the last occurrence of the specified
element) element in this list, or -1.
import java.util.*;
public class LinkedlistExample{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();// creating linked
list
al.add("Rachit"); // adding elements
al.add("Rahul");
al.add("Rajat");
Iterator<String> itr = al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
The output of the above program would be:
Rachit
Rahul
Rajat
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
The Queue interface provides several methods for adding, removing, and inspecting
elements in the queue. 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.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
element(): Returns the element at the front of the queue without removing it. If the
queue is empty, it throws an exception.
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.LinkedList;
import java.util.Queue;
public class Queue1
{
public static void main(String[] args)
{
Queue<String> queue = new LinkedList<>();
queue.add("apple");
queue.add("banana");
queue.add("cherry");
System.out.println("Queue: " + queue);
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Example2:
import java.util.LinkedList;
import java.util.Queue;
public class Queue2{
public static void main(String[] args)
{
Queue<Integer> q= new LinkedList<>();
for (int i = 0; i < 5; i++)
q.add(i);
System.out.println("Elements of queue "+ q);
// To remove the head of queue.
int removedele = q.remove();
System.out.println("removed element-"+ removedele);
System.out.println(q);
// To view the head of queue
int head = q.peek();
System.out.println("head of queue-"+ head);
int size = q.size();
System.out.println("Size of queue-"+ size);
}
}
Output:
Output
Elements of queue [0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
The set is an interface available in the java.util package. The set interface extends the
Collection interface. An unordered collection or list in which duplicates are not allowed is
referred to as a collection interface. The set interface is used to create the mathematical
set. The set interface use collection interface's methods to avoid the insertion of the same
elements. SortedSet and NavigableSet are two interfaces that extend the set
implementation.
SetExample1.
import java.util.*;
public class setExample{
public static void main(String[] args)
{
Set<String> data = new LinkedHashSet<String>();
data.add("Raju");
data.add("Stuti");
data.add("Pankaj");
data.add("Sumit");
System.out.println(data);
}
}
Output:
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
In set, addAll() method is used to perform the union, retainAll() method is used to
perform the intersection and removeAll() method is used to perform difference. Let's
take an example to understand how these methods are used to perform the intersection,
union, and difference operations.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
System.out.println(intersection_data);
Output:
Methods of Set
The Set interface includes all the methods of the Collection interface. It's
because Collection is a super interface of Set.
Some of the commonly used methods of the Collection interface that's also
available in the Set interface are:
• add() - adds the specified element to the set
• addAll() - adds all the elements of the specified collection to the set
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
• iterator() - returns an iterator that can be used to access elements of the set
sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another
specified set
• retainAll() - retains all the elements in the set that are also present in another
specified set
• clear() - removes all the elements from the set
• size() - returns the length (number of elements) of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element
• containsAll() - returns true if the set contains all the elements of the specified
collection
• hashCode() - returns a hash code value (address of the element in the set)
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Output
Set1: [2, 3]
Set2: [1, 2]
Union is: [1, 2, 3]
contains() Searches the HashSet for the specified element and returns a boolean result
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
The Map interface of the Java collections framework provides the functionality
of the map data structure.
Working of Map
In Java, elements of Map are stored in key/value pairs. Keys are unique
values associated with individual Values.
A map cannot contain duplicate keys. And, each key is associated with a
single value.
We can access and modify values using the keys associated with them.
In the above diagram, we have values: United States, Brazil, and Spain. And
we have corresponding keys: us, br, and es.
Note: The Map interface maintains 3 different sets:
• the set of keys
• the set of values
• the set of key/value associations (mapping).
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Methods of Map
The Map interface includes all the methods of the Collection interface. It is
because Collection is a super interface of Map .
Besides methods available in the Collection interface, the Map interface also includes the
following methods:
• put(K, V) - Inserts the association of a key K and a value V into the map. If the key is
already present, the new value replaces the old value.
• putAll() - Inserts all the entries from the specified map to this map.
• putIfAbsent(K, V) - Inserts the association if the key K is not already associated with
the value V .
• get(K) - Returns the value associated with the specified key K. If the key is not found,
it returns null.
• getOrDefault(K, defaultValue) - Returns the value associated with the specified key K.
If the key is not found, it returns the defaultValue.
• containsKey(K) - Checks if the specified key K is present in the map or not.
• containsValue(V) - Checks if the specified value V is present in the map or not.
• replace(K, V) - Replace the value of the key K with the new specified value V.
• replace(K, oldValue, newValue) - Replaces the value of the key K with the new
value newValue only if the key K is associated with the value oldValue.
• remove(K) - Removes the entry from the map represented by the key K.
• remove(K, V) - Removes the entry from the map that has key K associated with
value V.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Java HashMap
The HashMap class of the Java collections framework provides the functionality
of the hash table data structure.
It stores elements in key/value pairs. Here, keys are unique identifiers used
to associate each value on a map.
The HashMap class implements the Map interface.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Create a HashMap
In order to create a hash map, we must import the java.util.HashMap package
For example,
HashMap<String, Integer> numbers = new HashMap<>();
Here, the type of keys is String and the type of values is Integer .
Example 1: Create HashMap in Java
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> languages = new HashMap<>();
// add elements to hashmap
languages.put("Java", 8);
languages.put("JavaScript", 1);
languages.put("Python", 3);
System.out.println("HashMap: " + languages);
}
}
Output
HashMap: {Java=8, JavaScript=1, Python=3}
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// create a hashmap
HashMap<String, Integer> numbers = new HashMap<>();
class Main {
public static void main(String[] args) {
import java.util.HashMap;
class Main {
public static void main(String[] args) {
import java.util.HashMap;
class Main {
public static void main(String[] args) {
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Java LinkedHashMap
Creating a LinkedHashMap
In order to create a linked hashmap, we must import the java.util.LinkedHashMap package first.
Methods of LinkedHashMap
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
// Using putAll()
numbers.putAll(evenNumbers);
System.out.println("New LinkedHashMap: " + numbers);
}
}
Output
Original LinkedHashMap: {Two=2, Four=4}
Updated LinkedHashMap: {Two=2, Four=4, Six=6}
New LinkedHashMap: {One=1, Two=2, Four=4, Six=6}
import java.util.LinkedHashMap;
class Main {
public static void main(String[] args) {
LinkedHashMap<String, Integer> numbers = new LinkedHashMap<>();
numbers.put("One", 1);
numbers.put("Two", 2);
numbers.put("Three", 3);
System.out.println("LinkedHashMap: " + numbers);
// Using entrySet()
System.out.println("Key/Value mappings: " + numbers.entrySet());
// Using keySet()
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
// Using values()
System.out.println("Values: " + numbers.values());
}
}
Output
LinkedHashMap: {One=1, Two=2, Three=3}
Key/Value mappings: [One=1, Two=2, Three=3]
Keys: [One, Two, Three]
Values: [1, 2, 3]
Other Methods of LinkedHashMap
Method Description
containsKey() checks if the map contains the specified key and returns a boolean value
containsValue() checks if the map contains the specified value and returns a boolean value
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
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.
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Difference between HashMap and Hashtable
HashMap Hashtable
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
2) HashMap allows one null key and multiple null Hashtable doesn't allow any null key or
values. value.
5) We can make the HashMap as synchronized by calling Hashtable is internally synchronized and can't
this code be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Sorting in Collection
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If collection elements are of
use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the e
elements.
Note: String class and Wrapper classes implement the Comparable interface. So if
you store the objects of string or wrapper classes, it will be Comparable.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Tahir
Viru
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Collections.sort(al,Collections.reverseOrder());
Iterator i=al.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Viru
Tahir
Saurav
Mukesh
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns
o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
Example of the Comparable interface that sorts the list elements on the basis of age.
File: Student.java
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
File: TestSort1.java
import java.util.*;
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
105 Jai 21
101 Vijay 23
106 Ajay 27
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any
data member, for example, rollno, name, age or anything else.
public int compare(Object obj1, Object obj2) It compares the first object with the second object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Example:
File: Student.java
class Student {
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
File: TestSort1.java
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
import java.util.*;
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
/Sorting elements on the basis of name
Comparator<Student> cm1=Comparator.comparing(Student::getName);
Collections.sort(al,cm1);
System.out.println("Sorting by Name");
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
//Sorting elements on the basis of age
Comparator<Student> cm2=Comparator.comparing(Student::getAge);
Collections.sort(al,cm2);
System.out.println("Sorting by Age");
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by Age
105 Jai 21
101 Vijay 23
106 Ajay 27
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.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Properties(Properties defaults) It creates an empty property list with the specified defaults.
To get information from the properties file, create the properties file first.
db.properties
user=system
password=oracle
Now, let's create the java class to read the data from the properties file.
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:system
oracle
Example of Properties class to get all the system properties
By System.getProperties() method we can get all the properties of the system. Let's create
the class that gets information from the system properties.
DHANANJAYSHARMAOFFICIALS
Object Oriented Programming with Java [BCS 403]
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
DHANANJAYSHARMAOFFICIALS