Collections
• Collection in Java is a framework that provides an architecture
to store and manipulate the group of objects.
• 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).
Collections
• It provides readymade architecture.
• It represents a set of classes and interfaces.
• It is optional.
Iterable Interface
The Iterable interface is the root interface for all
the collection classes. The Collection interface
extends the Iterable interface and therefore all the
subclasses of Collection interface also implement
the Iterable interface.
It contains only one abstract method.
Iterator<T> iterator()
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.
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.
List Interface
• List interface is the child interface of Collection
interface. It inhibits a list type data structure in
which we can store the ordered collection of
objects. It can have duplicate values.
• List interface is implemented by the classes
ArrayList, LinkedList, Vector, and Stack.
ArrayList
• ArrayList inherits AbstractList class and implements the List
interface.
• Order of adding is preserved.
• ArrayList is initialized by size. However, the size is increased
automatically if the collection grows or shrinks if the objects are
removed from the collection.
• Java ArrayList allows us to randomly access the list.
• ArrayList can not be used for primitive types, like int, char, etc. We
need a wrapper class for such cases.
• ArrayList in Java can be seen as a vector in C++.
• ArrayList is not Synchronized. Its equivalent synchronized class in
Java is Vector.
import java.util.*;
public class Demo {
public static void main(String[] args) {
ArrayList<String> myfriendlist=new ArrayList<String>();
myfriendlist.add("Rohit");
myfriendlist.add("Virat");
myfriendlist.add("Hardik");
myfriendlist.add("Rishabh");
myfriendlist.add("Jasprit");
System.out.println(myfriendlist);
System.out.println(myfriendlist);
}
}
import java.util.ArrayList;
public class Demo1 {
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add(1);
al.add("Ram");
al.add(true);
al.add(67.90f);
Adding different type of objects
al.add(9087433); In arraylist
System.out.println(al);
}
}
import java.util. *;
class Student {
int roll,marks;
String name, branch;
public Student(int roll, int marks, String name, String branch) {
super();
this.roll = roll; this.marks = marks; this.name = name; this.branch = branch;
}
}
public class Demo1 {
public static void main(String[] args) {
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(1, 78, "Ganesh", "CSE"));
al.add(new Student(2, 70, "Krishna", "CSE"));
al.add(new Student(3, 71, "Ram", "CSE"));
al.add(new Student(4, 74, "Shiva", "CSE"));
al.forEach((s)->print(s));
}
public static void print(Student s) {
System.out.println(s.name+ " "+ s.roll+" "+s.branch+" "+s.marks);
}
}
Sorting ArrayList
1. Comparator interface
2. Comparable interface
import java.util.*; public class Demo2 {
class Student1 public static void main(String[] args) {
{ ArrayList<Student1> arr=new ArrayList<Student1>();
int roll, marks; arr.add(new Student1(10, 56, "Rohit", "CSE"));
String name, branch; arr.add(new Student1(21, 65, "Virat", "AS"));
public Student1(int roll, int marks, String name, arr.add(new Student1(35, 72, "Shiva", "ECE"));
String branch) { arr.add(new Student1(14, 81, "Shivam", "EE"));
super(); arr.add(new Student1(54, 33, "Axar", "ME"));
this.roll = roll; arr.sort(new Comparator3());
this.marks = marks; for(Student1 s:arr)
this.name = name; {
this.branch = branch; System.out.println(s.roll+" "+s.name+" "+s.marks+"
} "+s.branch);
} }
class Comparator1 implements Comparator<Student1> }
{ }
@Override //SORTING ROLL NUMBER WISE
public int compare(Student1 o1, Student1 o2) {
return o2.roll-o1.roll;
}
}
//*Comparator interface
import java.util.*; public class Demo4 {
class Student2 implements public static void main(String[] args) {
Comparable<Student2> ArrayList<Student2> arr=new
{ ArrayList<Student2>();
int roll, marks; arr.add(new Student2(10, 56, "Rohit", "CSE"));
String name, branch; arr.add(new Student2(21, 65, "Virat", "AS"));
public Student2(int roll, int marks, arr.add(new Student2(35, 72, "Shiva", "ECE"));
String name, String branch) { arr.add(new Student2(14, 81, "Shivam", "EE"));
super(); arr.add(new Student2(54, 33, "Axar", "ME"));
this.roll = roll;this.marks = Collections.sort(arr);
marks;this.name = name; for(Student2 s:arr)
this.branch = branch; {
} System.out.println(s.roll+" "+s.name+"
@Override "+s.marks+" "+s.branch);
public int compareTo(Student2 o) { }
return (this.name).compareTo(o.name); }
} }
}
//* Comparable interface
LinkedList
• The elements in the linked
list are stored in containers.
The list holds the link to the
first container.
• We use an ArrayList for
storing and accessing data,
and LinkedList to manipulate
data.
• LinkedList has methods like
addFirst(), addLast(),
removeFirst(), removeLast(),
getFirst(), getLast()
import java.util.LinkedList;
public class DemoLink {
public static void main(String[] args) {
LinkedList<String> ll=new LinkedList<String>();
ll.add("Rohit");//add item
ll.add("Virat");ll.add("Axar");ll.add("Ravindra");ll.add("Surya");
System.out.println(ll);
ll.addFirst("Samson");//add at first position
ll.addLast("Bumrah");//add at last position
System.out.println(ll);
ll.add(2, "Rahul");//add at index
System.out.println(ll);
ll.remove();//remove head
System.out.println(ll);
ll.remove(3);//remove from index 3
ll.removeLast();//remove from last
System.out.println(ll);
System.out.println(ll.peek());//returns front
ll.offer("Siraj");//adds at the end
System.out.println(ll);
System.out.println(ll.contains("Hardik"));
}
}
Difference Between ArrayList and LinkedList
Parameters ArrayList LinkedList
Underlying Data Structure Array Doubly linked list
Slower compared to LikedListTime Faster than ArrayListTime Complexity
Insertion
Complexity : O(N) : O(1)
Slower compared to LikedListTime Faster than ArrayListTime Complexity
Deletion
Complexity : O(N) : O(1)
Traverse Bidirectional Bidirectional
Fast searching Time Complexity :
Searching Fast searching Time Complexity : O(N)
O(N)
Random Access Fast Slow
Memory inefficient. It stores the object
Memory efficient. It only stores the object in
Memory Usage and the pointers to next and previous
the list.
nodes.
Contiguous memory is allocated to all the
Memory Allocation Contiguous memory is not allocated.
objects.
The Set Interface
• A Set is a Collection that cannot contain duplicate elements. It
models the mathematical set abstraction.
• The Set interface contains only methods inherited from
Collection and adds the restriction that duplicate elements are
prohibited.
HashSet
•Part of the Java Collections Framework
•Implements the Set interface
•Does not allow duplicate elements
•Uses a hash table for storage
•No guaranteed order of elements
•Allows null values
•Not synchronized (not thread-safe)
•Provides constant time performance for basic operations (add,
remove, contains, and size)
•O(1) time complexity for add, remove, contains, and size methods
(under ideal conditions)
import java.util.HashSet; import java.util.HashSet;
public class SETDEMO { public class SETDEMO {
public static void main(String[] args) { public static void main(String[] args)
Set<String> {
s=Set.of("Narendra","Rahul","Sonia","Niti HashSet<String> hs=new
sh"); OR HashSet<String>();
HashSet<String> hs=new hs.add("Narendra");
HashSet<String>(s); hs.add("Rahul");hs.add("Sonia");
System.out.println(hs); hs.add("Nitish");
} System.out.println(hs);
} }
}
import java.util.HashSet;
class Employee1
{
String name;
int id;
int salary;
Employee1(String name,int id,int salary){
this.name=name;
this.id=id;
this.salary=salary;
}
}
public class SETDEMO {
public static void main(String[] args) {
HashSet<Employee1>employees=new HashSet<Employee1>();
employees.add(new Employee1 ("Shivam",11,20000));
employees.add(new Employee1 ("Alex",2,15000));
employees.add(new Employee1 ("Shyam",33,22000));
employees.add(new Employee1 ("Ganesha",4,24000));
for (Employee1 e : employees ) {
System.out.println(e.id+" "+e.name+" "+e.salary);
}
}
}
HashSet vs. Other Sets
HashSet:
• No order maintained
• Fast operations
LinkedHashSet:
• Maintains insertion order
• Slightly slower than HashSet
TreeSet:
• Maintains natural order (or custom order using Comparator)
• Slower than HashSet due to sorting
public class SETDEMO {
public class SETDEMO { public static void main(String[] args) {
public static void main(String[] args) { Set<Integer> s=Set.of(5,4,3,2,1);
Set<Integer> s=Set.of(5,4,3,2,1); LinkedHashSet<Integer> ts1=new
TreeSet<Integer> ts1=new LinkedHashSet<Integer>(s);
TreeSet<Integer>(s); System.out.println(ts1);
System.out.println(ts1); }
} }
}
Sorted Ordered set implements SortedSet
public class SETDEMO {
import java.util.TreeSet;
public static void main(String[] args) {
class Employee1 implements
TreeSet<Employee1>employees=new
Comparable<Employee1>
TreeSet<Employee1>();
{
employees.add(new Employee1
String name;
("Shivam",11,20000));
int id;
employees.add(new Employee1
int salary;
("Alex",2,15000));
Employee1(String name,int id,int salary){
employees.add(new Employee1
this.name=name;
("Shyam",33,22000));
this.id=id;
employees.add(new Employee1
this.salary=salary;
("Ganesha",4,24000));
}
for (Employee1 e : employees ) {
@Override
System.out.println(e.id+" "+e.name+"
public int compareTo(Employee1 o) {
"+e.salary);
return this.id-o.id;
}
}
}
}
}
Queue
•Implements the Collection interface
•Follows FIFO (First-In-First-Out) principle
•Used to hold elements prior to processing
•Order is maintained
•Allows duplicates
•May be bounded or unbounded
•Provides additional methods to insert, extract, and inspect elements
Queue Interface Methods
Insert Methods:
• add(E e): Inserts element, throws exception if fails
• offer(E e): Inserts element, returns false if fails
Remove Methods:
• remove(): Removes head, throws exception if empty
• poll(): Removes head, returns null if empty
Examine Methods:
• element(): Retrieves head, throws exception if empty
• peek(): Retrieves head, returns null if empty
LinkedList:
• Implements both List and Queue interfaces
• Unbounded, allows null elements
PriorityQueue:
• Elements ordered according to natural ordering or comparator
• Unbounded, does not permit null elements
• a PriorityQueue can be used when it is necessary to process
queue elements in accordance with their priority.
ArrayDeque:
• Resizable array implementation
• Bounded by available memory, does not permit null elements
Queue Priority Queue
Priority Queue is an extension of
Queue is a linear data structure.
Queue with priority factor embedded.
Follows First In First Out (FIFO) Serves the element with higher
algorithm to serve the elements. priority first.(on calling poll())
Enqueue and dequeue done in Enqueue and dequeue done in O(log
O(1). n) using binary heaps.
Used in algorithms such as Dijkstra’s
Used in algorithms such as Breadth
Algorithm, Prim’s Algorithms, CPU
First Search.
Scheduling.
import java.util.List;
import java.util.PriorityQueue;
Dequeue operation
public class DemoQueue {
perform with poll or remove method
public static void main(String[] args) {
List<Integer> items=List.of(1,2,3,4,5);
PriorityQueue<Integer> pq=new PriorityQueue<Integer>(items);
System.out.println(pq);
pq.poll();//remove head of the queue
System.out.println(pq);
pq.poll();
System.out.println(pq);
pq.poll();
System.out.println(pq);
pq.poll();
System.out.println(pq);
pq.poll();
System.out.println(pq);
}
}
import java.util.PriorityQueue;
public class DemoQueue {
public static void main(String[] args) { enqueue operation
PriorityQueue<Integer> pq=new perform with offer or add method
PriorityQueue<Integer>();
System.out.println(pq);
pq.offer(1);//remove head of the queue
System.out.println(pq);
pq.offer(2);
System.out.println(pq);
pq.offer(3);
System.out.println(pq);
pq.offer(4);
System.out.println(pq);
pq.offer(5);
System.out.println(pq);
}
}
import java.util.Comparator; public class DemoQueue {
import java.util.PriorityQueue; public static void main(String[] args)
class Task{ {
int priority;String hobby; PriorityQueue<Task> pq=new
public Task(int priority, String hobby) { PriorityQueue<Task>(new Comp1());
super(); pq.add(new Task(3,"Singing"));
this.priority = priority; pq.add(new Task(1,"Dancing"));
this.hobby = hobby; pq.add(new Task(4, "Studying"));
} pq.add(new Task(15, "Playing"));
@Override pq.forEach((s)->System.out.println(s));
public String toString() { }
return "["+priority + "," + hobby + "]"; }
}
}
class Comp1 implements Comparator<Task>
{
@Override
public int compare(Task o1, Task o2) {
return o1.priority-o2.priority;
}
}
*Example 1
public class DemoQueue {
import java.util.Comparator; public static void main(String[] args) {
import java.util.PriorityQueue; PriorityQueue<Task> pq=new
class Task{ PriorityQueue<Task>(new Comp1());
int priority;String hobby; pq.add(new Task(3,"Singing"));
public Task(int priority, String hobby) { pq.add(new Task(1,"Dancing"));
super(); pq.add(new Task(4, "Studying"));
this.priority = priority; pq.add(new Task(15, "Playing"));
this.hobby = hobby; pq.forEach((s)->System.out.println(s));
} }
@Override }
public String toString() {
return "["+priority + "," + hobby + "]";
}
}
class Comp1 implements Comparator<Task>
{
@Override
public int compare(Task o1, Task o2) {
return o1.priority-o2.priority;
}
}
*Example 2
MAP INTERFACE
Map Interface is present in java.util package represents a
mapping between a key and a value. Java Map interface is not a
subtype of the Collection interface. Therefore it behaves a bit
differently from the rest of the collection types. A map contains
unique keys.
CHARACTERISTICS OF A MAP
INTERFACE
1.A Map cannot contain duplicate keys and each key can map to
at most one value. Some implementations allow null key and
null values like the HashMap and LinkedHashMap, but some do
not like the TreeMap.
2.The order of a map depends on the specific implementations.
For example, TreeMap and LinkedHashMap have predictable
orders, while HashMap does not.
3.There are two interfaces for implementing Map in Java. They are
Map and SortedMap, and three classes: HashMap, TreeMap, and
LinkedHashMap.
Method Action Performed
clear() This method is used in Java Map Interface to clear and remove 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 is being mapped into the Map or not. It takes the key
containsKey(Object)
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 key in the
containsValue(Object)
Map. It takes the value 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 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.
This method is used in Java Map Interface to check for equality between two maps. It verifies whether the elements of one map
equals(Object)
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 mentioned in the parameter. It returns NULL when the
get(Object)
map contains no such mapping for the key.
hashCode() This method is used in Map Interface to generate a hashCode for the given map containing keys and values.
isEmpty() This method is used to check if a map is having any entry for key and value pairs. If no mapping exists, then this returns true.
This method is used in Map Interface to return a Set view of the keys contained in this map. The set is backed by the map, so
keySet()
changes to the map are reflected in the set, and vice-versa.
put(Object, Object) This method is used in Java Map Interface to associate the specified value with the specified key in this map.
putAll(Map) This method is used in Map Interface in Java to copy all of the mappings from the specified map to this map.
remove(Object) This method is used in Map Interface to remove the mapping for a key from this map if it is present in the map.
size() This method is used to return the number of key/value pairs available in the map.
This method is used in Java Map Interface to create a collection out of the values of the map. It basically returns a Collection view
values()
of the values in the HashMap.
getOrDefault(Object key, V defaultValue) Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
merge(K key, V value, BiFunction<? super
If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value.
V,? super V,? extends V> remappingFunction)
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,
putIfAbsent(K key, V value)
else returns the current associate value.
import java.util.HashMap;
import java.util.Map.Entry; HashMap Example 1
public class MapDemo {
public static void main(String...strings)
{
HashMap<Integer, String> hm=new HashMap<Integer, String>();
hm.put(11, "Shyam");hm.put(4, "Rohit");hm.put(5, null);hm.put(2, "Ram");
for(Entry<Integer, String> e:hm.entrySet())
{
System.out.println(e.getKey()+" "+e.getValue());
}
}
}
import java.util.HashMap;
import java.util.Map.Entry; TreeMap Example 1
import java.util.TreeMap;
public class MapDemo {
public static void main(String...strings)
{
TreeMap<Integer, String> hm=new TreeMap<Integer, String>();
hm.put(1, "Shyam");hm.put(4, "Rohit");hm.put(31, "Axar");hm.put(2, "Ram");
for(Entry<Integer, String> e:hm.entrySet())
{
System.out.println(e.getKey()+" "+e.getValue());
}
}
}
import java.util.Comparator; public class MapDemo {
import java.util.Map.Entry; public static void main(String...strings)
import java.util.TreeMap; {
class SomeData TreeMap<SomeData, String> hm=new
{ TreeMap Example 2 TreeMap<SomeData, String>(new CompSomeData());
int k; hm.put(new SomeData(5), "Shyam");hm.put(new
public SomeData(int k) { SomeData(6), "Rohit");hm.put(new SomeData(7),
super(); "Axar");hm.put(new SomeData(8), "Ram");
this.k = k; for(Entry<SomeData, String> e:hm.entrySet())
} {
@Override System.out.println(e.getKey()+" and value is
public String toString() { "+e.getValue());
return "key is " + k + " "; }
} }
} }
class CompSomeData implements
Comparator<SomeData>
{
@Override
public int compare(SomeData o1, SomeData
o2) {
return o1.k-o2.k;
}
}
HASHTABLE IN JAVA
The java.util.Hashtable class is a class in Java that provides a key-
value data structure, similar to the Map interface. It was part of
the original Java Collections framework and was introduced in
Java 1.0.
Hashtable class has since been considered obsolete and its use is
generally discouraged.
The Hashtable class is synchronized, which can result in slower
performance compared to other implementations of the Map
interface.
In Java 1.2:
Hashtable was updated to implement the Map interface, making
it a member of the Java Collections Framework.
Features of Hashtable
• It is similar to HashMap, but is synchronized.
• Hashtable stores key/value pair in hash table.
• In Hashtable we specify an object that is used as a key, and the
value we want to associate to that key. The key is then hashed,
and the resulting hash code is used as the index at which the
value is stored within the table.
• The initial default capacity of Hashtable class is 11 whereas
loadFactor is 0.75.
• HashMap doesn’t provide any Enumeration, while Hashtable
provides not fail-fast Enumeration.
• Both key and value can not be null.
import java.util.Enumeration;
import java.util.Hashtable; # PROGRAM 1
public class MapDemo {
public static void main(String...strings){
Hashtable<String, Integer> hashtable = new Hashtable<>();
hashtable.put("A", 1);
hashtable.put("B", 2);
hashtable.put("C", 3);
// Getting values from the hashtable
int valueA = hashtable.get("A");
System.out.println("Value of A: " + valueA);
// Removing elements from the hashtable
hashtable.remove("B");
// Enumerating the elements of the hashtable
Enumeration<String> keys = hashtable.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
System.out.println("Key: " + key + ", Value: " + hashtable.get(key));
}}}
import java.util.Hashtable;
import java.util.Map.Entry; # PROGRAM 2
public class HTDemo {//Hash tables are synchronised
public static void main(String[] args) {
Hashtable<Integer, String> ht=new Hashtable<Integer, String>();
ht.put(12,"ALEX");//hashtable implements Map interface
ht.put(3,"SCOTT");
//ht.put(null,"ROY");//Error null keys not supported
ht.put(11,"MITCHELL");
ht.put(7,"JOHN");
//ht.put(5, null);//Error null values not supported
for(Entry<Integer, String> e:ht.entrySet())
{
System.out.println(e.getKey()+" "+e.getValue());
}
}
}
PROPERTIES CLASS IN JAVA
The Properties class represents a persistent set of properties.
The Properties can be saved to a stream or loaded from a
stream. It belongs to java.util package.
•Properties is a subclass of Hashtable.
•It is used to maintain a list of values in which the key is a String and the
value is also a string i.e; it can be used to store and retrieve string type data
from the properties file.
•Properties class can specify other properties list as it’s the default. If a
particular key property is not present in the original Properties list, the
default properties will be searched.
•Properties object does not require external synchronization and Multiple
threads can share a single Properties object.
•Also, it can be used to retrieve the properties of the system.
import java.io.FileWriter; import java.io. *;
import java.io.IOException; import java.util.Iterator;
import java.util.Properties; import java.util.Map.Entry;
public class Temp { import java.util.Properties;
public static void main(String[] args) import java.util.Set;
throws IOException { public class Temp {
Properties p=new Properties(); public static void main(String[] args) throws
p.setProperty("username", "scott"); IOException {
p.setProperty("password", "tiger"); Properties p=new Properties();
p.store(new FileWriter("db.properties"),
"saving user name and password"); p.load(new
System.out.println("saved successfully"); FileReader("db.properties"));
} Set s=p.entrySet();
} Iterator i=s.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}