0% found this document useful (0 votes)
50 views38 pages

Collection Framework 1

The document provides an overview of the Java Collection Framework, which includes various interfaces and classes for storing and managing groups of objects. It covers key components such as List, Set, and Map interfaces, along with their implementations like ArrayList, LinkedList, HashSet, and HashMap. Additionally, it explains methods associated with these collections and the differences between Comparable and Comparator interfaces for sorting objects.
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)
50 views38 pages

Collection Framework 1

The document provides an overview of the Java Collection Framework, which includes various interfaces and classes for storing and managing groups of objects. It covers key components such as List, Set, and Map interfaces, along with their implementations like ArrayList, LinkedList, HashSet, and HashMap. Additionally, it explains methods associated with these collections and the differences between Comparable and Comparator interfaces for sorting objects.
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/ 38

Collection Framework

Introduction to Collections

• Collections in Java provide an architecture to store and manipulate groups of

objects.

• It is a framework with several useful interfaces and classes.

• Helps in managing and processing data efficiently.


Framework in Java

• A framework is prewritten code used to create applications

in Java.

• It provides a standard way to build and deploy applications.


Collection Framework

•A unified architecture for storing and managing objects.

•Includes various interfaces and classes for different data structures.


Collection Framework Hierarchy
Collection Framework Hierarchy
Methods present in the
collection interface
Method Description
add(Object o) To insert an element in the collection.
addAll(Collection c) To insert another collection in the present collection.
remove(Object o) To remove an element in the collection.
To remove another collection from the present collection if
removeAll(Collection c)
another is inserted.
To remove all the collection elements that are not contained in
retain(collection c)
the specified collection.
clear() It removes all the elements from the collection.
isEmpty() It checks collection is empty or not and provides true or false.
It gives the total number of elements present in the collection
size()
in form of a numeric value.
equals(collection c) It is used to check if the two collections are the same or not.
toArray(collection c) It converts collection into an array.
It is used for searching. If an element is present in the
contains(Object o)
collection it returns true or false.
List Interface

• The list is a child interface of Collections in java.


• Insertion order preserved i.e., They appear in the same order in which we
inserted.
• Duplicate elements are allowed.

List Interface is implemented by using ArrayList, LinkedList, and Vector


class.
ArrayList

• ArrayList is a class present in java.util package.

• It provides a dynamic array for storing the element.

• It is an array but there is no size limit.

• We can add or remove elements easily.

• It is more flexible than a traditional array.

Syntax:
ArrayList<DataType> VariableName=new ArrayList<DataType>( )
For example,
1. This is way is to store values of the same datatype
import java.util.*;
public class ListArryList
{
public static void main(String[] args {
ArrayList < String>name =new ArrayList<String>();
name.add("Pinku');
name.add("seeta");
name.add("geeta");
name.add("sara");
name.add("ved');
System.out.println(name); }
}
This is way is to store values of different datatype
import java.util.*;
public class ListArraylist
{ public static void main(String[]args)
{ ArrayList name= new ArrayList();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}
Methods in ArrayList:
Description
Method

It prints the value at a specific


get(object o) index.
It updates the value. In that, we
set(index, object o) need to provide an index.
It adds an element at a specific
add(index, object o) index.
It removes elements at specific
remove(Object o) indexes.
It sorts an array depending upon
sort() the data type.
It is used to add another
addAll(Collection c) collection.
LinkedList
• LinkedList class uses a doubly LinkedList to store element. i.e., the user can add

data at the first position as well as the last position.

• The dequeue interface is implemented using the LinkedList class.

• Null insertion is possible.

• If we need to perform insertion /Deletion operation the LinkedList is preferred.

• LinkedList is used to implement Stacks and Queues.

Syntax:

LinkedList<DataType> VariableName = new LinkedLits < DataType>();


Methods in LinkedList:

addFirst()
addLast()
removeFirst()
removeLast()
getFirst()
getLast()
import java.util.*;
public class Main { public static void main(String[] args)
{
LinkedList<String> list = new LinkedList<String>();
list.add("C");
list.add("C++");
list.add("Python");
list.add("Java");
list.add("PHP");
System.out.println("Original list is: "+ list);
System.out.println("After adding element by using
getFirst() method: " + list.getFirst());
list.addLast("CSS");
System.out.println("After adding element by using
addLast() method: " + list); list.removeLast();
System.out.println("After adding element by using
removeLast() method: " + list); System.out.println("After
adding element by using getLast() method: " +
list.getLast()); } }
Vector
• Every method is synchronized.

• The vector object is Thread safe.

• At a time only one thread can operate on the Vector object.

• performance is low because Threads are needed to wait.

How to create a list using vector

Vector < DataType> VariableName = new Vector<DataType> ();


Methods in vector
addElement()
firstElement()
lastElement()

import java.util.*;
public class Main { public static void main(String[] args)
{ Vector<String> lis = new Vector<String>();
System.out.println("In vector addElement() method is also used to add elements ");
lis.add("Tiger");
lis.add("Lion");
lis.add("Dog");
lis.add("Elephant");
lis.addElement("Deer");
System.out.println(lis);
System.out.println("The first animal is = "+lis.firstElement());
System.out.println("The last animal is = "+lis.lastElement()); } }
Set Interface

• Set is a child interface of Collection.

• Insertion order not preserved i.e., They appear in the different order in which

we inserted.

• Duplicate elements are not allowed.

• Heterogeneous objects are allowed.


Hashset

• HashSet stores the elements by using Hashing mechanism.

• It contains unique elements only.

• This hashSet allows null values.

• It does not maintain insertion order. It inserted elements based

on their hashcode.

• HashSet is the best approach for the search operation.


Create HashSet
There are three different ways to create HashSet:
1.HashSet hs = new Hashset();
Here, HashSet default capacity to store elements is 16 with a default load
factor/fill ratio of 0.75.
Load factor is if HashSet stores 75% element then it creates a new
HashSet with increased capacity.
2. Hashset hs = new Hashset ( 100);
Here 100 is an initial capacity and the default load factor is 0.75.
3. Hashset hs = new Hashset ( 100,(foot) 0.90);
Here capacity is 100 with a load factor of 0.90. The load factor
Example- Remove duplicate elements.

import java.util.*;
public class Main { public static void main(String[] args)
{
int a[]={1,1,1,2,3,5,5,5,6,6,9,9,9,9};
HashSet<Integer> hs = new HashSet<Integer>();
for(int i=0;i<a.length;i++) { hs.add(a[i]);
}
for(int i:hs)
{
System.out.print(i+" ");
}}
TreeSet
• Java TreeSet class implements the Set interface that uses a tree structure to store

elements.

• It contains Unique Elements.

• TreeSet class access and retrieval time are very fast.

• It does not allow null elements.

• It maintains Ascending Order.


Example
import java.util.*;
public class Main {
public static void main(String[] args) {
TreeSet <String> animal=new
TreeSet<String>(); animal.add("Dog");
animal.add("Tiger");
animal.add("Lion");
animal.add("Fox");
animal.add("Rabbit");
System.out.println(animal);
System.out.println(animal.descendingSet());
System.out.println(animal.pollFirst());
System.out.println(animal.polllast());
System.out.println(animal.headset("Lion"));
System.out.println(animal.tailSet("Fox")); } }
Map Interface
• A map is a part of the collection framework but it does not implement a collection
interface.

• A map stores values based on Key and value Pair.

• Duplicate value of the key is not allowed.


• Key must be unique while duplicates values are allowed.

Sub Interfaces fo Map:


HashMap
LinkedHashMap
Hashtable
HashMap
• Map Interface is implemented by HashMap.
• HashMap stores the elements by using a mechanism called Hashing.
• It contains values based on the key-value pair.
• It contains a unique key.
• It can store one Null key and Multiple null values.
• Insertion order is not maintained and it is based on the hash code of the keys.
• HashMap is Non-Synchronized.
How to create HashMap:
HashMap < dataType, dataType> m = new HashMap < dataType,dataType>();
import java.util.*;
System.out.println(m);
public class Main public static void
System.out.println(m.containsKey(2));
main(String[] args) { HashMap
System.out.println(m.containsValue("neeta"));
<Integer, String> m = new HashMap
System.out.println(m.containsKey(6));
<Integer, String>();
System.out.println(m.containsValue("jeena"));
m.put(1,"seeta");
System.out.println(m.isEmpty());
m.put(2,"geeta");
System.out.println(m.keySet());
m.put(3,"reeta");
System.out.println(m.values());
m.put(4,"neeta");
System.out.println(m.entrySet());
m.put(5,"piku");
System.out.println("Method to print key and
System.out.println(m);
values together");
System.out.println(m.get(5));
for(Object i:m.keySet())
m.remove(3);
Hashtable
• A Hashtable is an array of lists. Each list is known as a bucket.

• A hashtable contains values based on key-value pair.

• It contains unique elements only.

• Hashtable class does not allow null key as well as value otherwise it will throw

NullPointerException.

• Every method is synchronized. i.e At a time only one thread is allowed and the other

threads are on a wait.

• Performance is poor as compared to HashMap.


How to create HashMap

Hashtable t = new Hashtable();

1.Here default capacity is 11, the load factor is 0.75. (Load factor refer HashSet)

Hashtable t = new hashtable ( initial Capacity );

Here Hashtable is created with some capacity

Hashtable t = new hashtable ( initial capacity, fillration/load factor);


Iterator
• An Iterator in Java is an interface used to traverse elements in a Collection

sequentially.

• It provides methods like hasNext(), next(), and remove() to loop through

collections and perform manipulation.

• An Iterator is a part of the Java Collection Framework, and we can use it with

collections like ArrayList, LinkedList, and other classes that implement the

Collection interface.
import java.util.ArrayList;
Iterator<String> it = al.iterator();
import java.util.Iterator;
while (it.hasNext()) {
public class qwerty {
public static void main(String[] args) {
String n = it.next();
System.out.println(n);
ArrayList<String> al = new ArrayList<>();
}
al.add("A");
}
al.add("B");
al.add("C");
}
import java.util.*; for (Student s : students) {
public class SortExampleDemo {
System.out.println("forEach" + s);
public void sortStudentInfo() {
ArrayList<Student> students = new }
ArrayList<Student>();
System.out.println("**********Traverse item
students.add(new Student(1, "Galu", using forEach*****");
"galu@gmail.com"));
students.add(new Student(4, "Koko",
"koko@gmail.com")); students.forEach(System.out::println);
students.add(new Student(2, "Gugi", }
"gugi@gmail.com")); public static void main(String[] args) {
students.add(new Student(3, "shree",
SortExampleDemo sortExampleDemo = new
"shree@gmail.com"));
Collections.sort(students); SortExampleDemo();
sortExampleDemo.sortStudentInfo();
System.out.println("*****Traverse item using iterator*********"); }
}
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Comparable Interface
1.The Comparable interface is used to define the natural ordering of objects. If a class

implements the Comparable interface, it means that instances of that class can be compared

and sorted based on their natural order.

2. This interface has only one method: compareTo(Object obj)

3. In the compareTo method, we need to compare two objects.

If the current object is greater, a positive integer should be returned. If the current object is

smaller, a negative integer should be returned. If both objects are equal, zero should be

returned.
public class Student implements return "Student{" +
Comparable<Student> "id=" + id +
{ ", name='" + name + '\'' +
int id; ", email='" + email + '\'' +
String name; '}';
String email; }
public Student(int id, String name, String email) { public int compareTo(Student
this.id = id; studentObj) {
this.name = name; return
this.email = email; this.name.compareTo(studentObj.name);
} }}
public String toString() {
Comparator Interface
1.Comparator interface in Java is used to order the objects of user-defined
classes.
2.A comparator object is capable of comparing two objects of the same
class.
3.The Comparator interface is used to define a custom way of comparing objects.
It is particularly useful when you want to provide multiple sorting options for a
class.
4.The Comparator interface has a compare method that takes two objects and
returns a negative integer, zero, or a positive integer if the first object is less than,
equal to, or greater than the second object, respectively.
import java.util.*; class SortbyRoll implements
class Student { Comparator<Student>
int rollno; {
String name; public int compare(Student a, Student b) {
return a.rollno - b.rollno;
Student(int rollno, String name) { }
this.rollno = rollno; }
this.name = name;
}
public String toString() {
return rollno + ": " + name;
}
}
System.out.println("Sorted by Roll
public class GFG Number ");
{ for (int i = 0; i < students.size(); i++)
public static void main(String[] args)
{ System.out.println(students.get(i));
List<Student> students = new ArrayList<>();
}
students.add(new Student(111, "Mayank")); }
students.add(new Student(131, "Anshul")); Output
students.add(new Student(121, "Solanki")); Sorted by Roll Number
students.add(new Student(101, "Aggarwal")); 101: Aggarwal
Collections.sort(students, new SortbyRoll()); 111: Mayank
121: Solanki
131: Anshul
Difference Between Comparable and
Comparator
Comparable Comparator
It defines natural ordering within the
It defines external sorting logic.
class.
compareTo() compare()

It is implemented in the class. It is implemented in a separate class.

Natural order sorting Custom sorting

It is used for single sorting order. It is used for multiple sorting orders.
THANK
YOU

You might also like