SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Collection Framework
Handled By
Dr.T.Abirami
Associate Professor
Department of IT
Kongu Engineering College Perundurai
What is a Framework?
• A framework is a set
of classes and interfaces which provide a ready-
made architecture.
• An optimal object-oriented design always
includes a framework with a collection of classes
such that all the classes perform the same kind
of task.
Collections in Java / Collections
Framework
• The Java collections framework provides a set
of interfaces and classes to implement various
data structures and algorithms.
• Java Collections can achieve all the operations
that you perform on a data such as searching,
sorting, insertion, manipulation, and
deletion.
What is Collection in Java
• Java Collection means a single unit of objects.
(i.e., a group)
• Java Collection framework provides many
interfaces
(Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue,
HashSet, LinkedHashSet, TreeSet).
Hierarchy of Collection Framework
Methods of Collection interface
No. Method Description
1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean addAll(Collection<?
extends E> c)
It is used to insert the specified collection elements in the invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.
4 public boolean
removeAll(Collection<?> c)
It is used to delete all the elements of the specified collection from the invoking
collection.
5 default boolean removeIf(Predicate<?
super E> filter)
It is used to delete all the elements of the collection that satisfy the specified
predicate.
6 public boolean retainAll(Collection<?>
c)
It is used to delete all the elements of invoking collection except the specified
collection.
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the collection.
9 public boolean contains(Object
element)
It is used to search an element.
10 public boolean
containsAll(Collection<?> c)
It is used to search the specified collection in the collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the returned array is
that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.
List Interface
• To store the ordered collection of objects. It
can have duplicate values.
• List interface is implemented by the classes
ArrayList, LinkedList, Vector, and Stack.
Example
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
The classes that implement the List
interface are given below.
ArrayList :
• The ArrayList class implements the List
interface.
• It uses a dynamic array to store the duplicate
element of different data types.
• The ArrayList class maintains the insertion
order and is non-synchronized.
• The elements stored in the ArrayList class can
be randomly accessed.
Java Iterators
• to access every item in a collection of items - We
call this traversing or iterating
• Example: array for
(inti = 0; i < array.length; i++)
// do something with array[i]
• Java provides an interface for stepping through all
elements in any collection, called an iterator
Iterating through an ArrayList
• Iterating through an ArrayListn Iterating through an
ArrayList of Strings:
for (int i = 0; i < list.size(); i++)
{
String s = list.get(i); //do something with s
}
Alternative:
Iterator<String> itr = list.iterator();
while (itr.hasNext())
{
String s = list.next();
}
This syntax of iteration is generic and
applies to any Java class that implements
the Iterator interface
the code will work even if we decide to store
the data in a different data structure (as long
as it provides an iterator)
Iterator Interface
Iterator<T>: - a generic interface with the following
methods
• public booleanhasNext(); returns true if there are
more elements to iterate over
• public T next(); returns the next element
– throws a NoSuchElement exception if a next element
does not exist
• public void remove(); removes the last element
returned by the iterator (optional operation)
• It is in the java.utilpackage
ArrayList :
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
• LinkedList implements the Collection interface.
• It uses a doubly linked list internally to store the
elements.
• It can store the duplicate elements. It
maintains the insertion order and is not
synchronized.
• In LinkedList, the manipulation is fast because
no shifting is required.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
LinkedList
Output:
Ravi
Vijay
Ravi
Ajay
Vector
• Vector uses a dynamic array to store the data
elements.
• It is similar to ArrayList.
• However, It is synchronized and contains many
methods that are not the part of Collection
framework.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Vector
Stack
• The stack is the subclass of Vector.
• It implements the last-in-first-out data
structure, i.e., Stack.
• The stack contains all of the methods of
Vector class and also provides its methods like
boolean push(),
boolean peek(),
boolean push(object o), which defines its
properties.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Stack
HashSet
• to create a collection that uses a hash table for
storage.
• It inherits the AbstractSet class and implements Set
interface.
• It stores the elements by using a mechanism
called hashing.
• It contains unique elements only.
• It allows null value.
• HashSet class is non synchronized.
• It doesn't maintain the insertion order. Here, elements
are inserted on the basis of their hashcode.
• It is the best approach for search operations.
Difference between List and Set
• A list can contain duplicate elements whereas
Set contains unique elements only.
HashSet example ignoring duplicate
elements
import java.util.*;
class HashSet2{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi
Java Collections – Map
• A Map is an object that maps keys to values.
• A map cannot contain duplicate keys.
• There are three main implementations of Map
interfaces: HashMap, TreeMap, and
LinkedHashMap.
• HashMap: it makes no guarantees concerning the
order of iteration
• TreeMap: It stores its elements in a red-black tree,
orders its elements based on their values; it is
substantially slower than HashMap.
• LinkedHashMap: It orders its elements based on the
order in which they were inserted into the set
(insertion-order).
HashMap
• HashMap is a Map based collection class that
is used for storing Key & value pairs,
• it is denoted as HashMap<Key, Value> or
HashMap<K, V>.
• This class makes no guarantees as to the order
of the map.
• It is similar to the Hashtable class except that
it is unsynchronized and permits nulls(null
values and null key).
HashMap
• It is not an ordered collection
• which means it does not return the keys and
values in the same order in which they have
been inserted into the HashMap.
• It does not sort the stored keys and Values.
• to import java.util.HashMap or its super class
in order to use the HashMap class and
methods.
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,St
ring>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// create an array list to store Integer data
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(4);
list1.add(5);
System.out.println("ArrayList of Integer: " + list1);
// creates an array list to store String data
ArrayList<String> list2 = new ArrayList<>();
list2.add("Four");
list2.add("Five");
System.out.println("ArrayList of String: " + list2);
// creates an array list to store Double data
ArrayList<Double> list3 = new ArrayList<>();
list3.add(4.5);
list3.add(6.5);
System.out.println("ArrayList of Double: " + list3);
}
}
Output
ArrayList of Integer:
[4, 5]
ArrayList of String:
[Four, Five]
ArrayList of Double:
[4.5, 6.5]
• we have used the same ArrayList class to store
elements of Integer, String, and Double types.
This is possible because of Java Generics.
• Here, notice the line,
• ArrayList<Integer> list1 = new ArrayList<>();
We have used Integer inside the angle
brackets, <>. The angle bracket, <> is known as
the type parameter in generics.
• The type parameter is used to specify the type
of objects (data) that the generics class or
method works on.

Weitere ähnliche Inhalte

Was ist angesagt?

Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in JavaAbhilash Nair
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
07 java collection
07 java collection07 java collection
07 java collectionAbhishek Khune
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java NotesShalabh Chaudhary
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda ExpressionsScott Leberknight
 
sets and maps
 sets and maps sets and maps
sets and mapsRajkattamuri
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packagesVINOTH R
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streamsHamid Ghorbani
 

Was ist angesagt? (20)

Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java threads
Java threadsJava threads
Java threads
 
Applets
AppletsApplets
Applets
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Java awt
Java awtJava awt
Java awt
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 

Ă„hnlich wie Java Collections

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxeyemitra1
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40bhawna sharma
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Java collections
Java collectionsJava collections
Java collectionsHamid Ghorbani
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_FrameworkKrishna Sujeer
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Lecture 9
Lecture 9Lecture 9
Lecture 9talha ijaz
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collectionsAbhijit Gaikwad
 
Javasession7
Javasession7Javasession7
Javasession7Rajeev Kumar
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structuresagorolabs
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection apiRakesh Madugula
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 

Ă„hnlich wie Java Collections (20)

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java collections
Java collectionsJava collections
Java collections
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Java util
Java utilJava util
Java util
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Java.util
Java.utilJava.util
Java.util
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collections
 
Javasession7
Javasession7Javasession7
Javasession7
 
Java 103 intro to java data structures
Java 103   intro to java data structuresJava 103   intro to java data structures
Java 103 intro to java data structures
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 

Mehr von Kongu Engineering College, Perundurai, Erode

A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...Kongu Engineering College, Perundurai, Erode
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Kongu Engineering College, Perundurai, Erode
 

Mehr von Kongu Engineering College, Perundurai, Erode (20)

Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...A REST API (also called a RESTful API or RESTful web API) is an application p...
A REST API (also called a RESTful API or RESTful web API) is an application p...
 
SOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptxSOA and Monolith Architecture - Micro Services.pptx
SOA and Monolith Architecture - Micro Services.pptx
 
Application Layer.pptx
Application Layer.pptxApplication Layer.pptx
Application Layer.pptx
 
Connect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptxConnect to NoSQL Database using Node JS.pptx
Connect to NoSQL Database using Node JS.pptx
 
Node_basics.pptx
Node_basics.pptxNode_basics.pptx
Node_basics.pptx
 
Navigation Bar.pptx
Navigation Bar.pptxNavigation Bar.pptx
Navigation Bar.pptx
 
Bootstarp installation.pptx
Bootstarp installation.pptxBootstarp installation.pptx
Bootstarp installation.pptx
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
Chapter 3.pdf
Chapter 3.pdfChapter 3.pdf
Chapter 3.pdf
 
Introduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdfIntroduction to Social Media and Social Networks.pdf
Introduction to Social Media and Social Networks.pdf
 
Dropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdfDropdown Menu or Combo List.pdf
Dropdown Menu or Combo List.pdf
 
div tag.pdf
div tag.pdfdiv tag.pdf
div tag.pdf
 
Dimensions of elements.pdf
Dimensions of elements.pdfDimensions of elements.pdf
Dimensions of elements.pdf
 
CSS Positioning Elements.pdf
CSS Positioning Elements.pdfCSS Positioning Elements.pdf
CSS Positioning Elements.pdf
 
Random number generation_upload.pdf
Random number generation_upload.pdfRandom number generation_upload.pdf
Random number generation_upload.pdf
 
JavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdfJavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdf
 
Computer Networks: Quality of service
Computer Networks: Quality of serviceComputer Networks: Quality of service
Computer Networks: Quality of service
 
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
Transport layer protocols : Simple Protocol , Stop and Wait Protocol , Go-Bac...
 
Transport layer services
Transport layer servicesTransport layer services
Transport layer services
 

KĂĽrzlich hochgeladen

complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...121011101441
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoĂŁo Esperancinha
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 

KĂĽrzlich hochgeladen (20)

complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...Instrumentation, measurement and control of bio process parameters ( Temperat...
Instrumentation, measurement and control of bio process parameters ( Temperat...
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 

Java Collections

  • 1. Collection Framework Handled By Dr.T.Abirami Associate Professor Department of IT Kongu Engineering College Perundurai
  • 2. What is a Framework? • A framework is a set of classes and interfaces which provide a ready- made architecture. • An optimal object-oriented design always includes a framework with a collection of classes such that all the classes perform the same kind of task.
  • 3. Collections in Java / Collections Framework • The Java collections framework provides a set of interfaces and classes to implement various data structures and algorithms. • Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
  • 4. What is Collection in Java • Java Collection means a single unit of objects. (i.e., a group) • Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
  • 6.
  • 7. Methods of Collection interface No. Method Description 1 public boolean add(E e) It is used to insert an element in this collection. 2 public boolean addAll(Collection<? extends E> c) It is used to insert the specified collection elements in the invoking collection. 3 public boolean remove(Object element) It is used to delete an element from the collection. 4 public boolean removeAll(Collection<?> c) It is used to delete all the elements of the specified collection from the invoking collection. 5 default boolean removeIf(Predicate<? super E> filter) It is used to delete all the elements of the collection that satisfy the specified predicate. 6 public boolean retainAll(Collection<?> c) It is used to delete all the elements of invoking collection except the specified collection. 7 public int size() It returns the total number of elements in the collection. 8 public void clear() It removes the total number of elements from the collection. 9 public boolean contains(Object element) It is used to search an element. 10 public boolean containsAll(Collection<?> c) It is used to search the specified collection in the collection. 11 public Iterator iterator() It returns an iterator. 12 public Object[] toArray() It converts collection into array. 13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the returned array is that of the specified array. 14 public boolean isEmpty() It checks if collection is empty. 15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its source. 16 default Stream<E> stream() It returns a sequential Stream with the collection as its source. 17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the collection. 18 public boolean equals(Object element) It matches two collections. 19 public int hashCode() It returns the hash code number of the collection.
  • 8. List Interface • To store the ordered collection of objects. It can have duplicate values. • List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack. Example List <data-type> list1= new ArrayList(); List <data-type> list2 = new LinkedList(); List <data-type> list3 = new Vector(); List <data-type> list4 = new Stack(); There are various methods in List interface that can be used to insert, delete, and access the elements from the list.
  • 9. The classes that implement the List interface are given below. ArrayList : • The ArrayList class implements the List interface. • It uses a dynamic array to store the duplicate element of different data types. • The ArrayList class maintains the insertion order and is non-synchronized. • The elements stored in the ArrayList class can be randomly accessed.
  • 10.
  • 11. Java Iterators • to access every item in a collection of items - We call this traversing or iterating • Example: array for (inti = 0; i < array.length; i++) // do something with array[i] • Java provides an interface for stepping through all elements in any collection, called an iterator
  • 12. Iterating through an ArrayList • Iterating through an ArrayListn Iterating through an ArrayList of Strings: for (int i = 0; i < list.size(); i++) { String s = list.get(i); //do something with s } Alternative: Iterator<String> itr = list.iterator(); while (itr.hasNext()) { String s = list.next(); } This syntax of iteration is generic and applies to any Java class that implements the Iterator interface the code will work even if we decide to store the data in a different data structure (as long as it provides an iterator)
  • 13. Iterator Interface Iterator<T>: - a generic interface with the following methods • public booleanhasNext(); returns true if there are more elements to iterate over • public T next(); returns the next element – throws a NoSuchElement exception if a next element does not exist • public void remove(); removes the last element returned by the iterator (optional operation) • It is in the java.utilpackage
  • 14. ArrayList : import java.util.*; class TestJavaCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>();//Creating arraylist list.add("Ravi");//Adding object in arraylist list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); //Traversing list through Iterator Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ravi Vijay Ravi Ajay
  • 15. LinkedList • LinkedList implements the Collection interface. • It uses a doubly linked list internally to store the elements. • It can store the duplicate elements. It maintains the insertion order and is not synchronized. • In LinkedList, the manipulation is fast because no shifting is required.
  • 16.
  • 17. import java.util.*; public class TestJavaCollection2{ public static void main(String args[]){ LinkedList<String> al=new LinkedList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } LinkedList Output: Ravi Vijay Ravi Ajay
  • 18. Vector • Vector uses a dynamic array to store the data elements. • It is similar to ArrayList. • However, It is synchronized and contains many methods that are not the part of Collection framework.
  • 19.
  • 20. import java.util.*; public class TestJavaCollection3{ public static void main(String args[]){ Vector<String> v=new Vector<String>(); v.add("Ayush"); v.add("Amit"); v.add("Ashish"); v.add("Garima"); Iterator<String> itr=v.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ayush Amit Ashish Garima Vector
  • 21. Stack • The stack is the subclass of Vector. • It implements the last-in-first-out data structure, i.e., Stack. • The stack contains all of the methods of Vector class and also provides its methods like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
  • 22. import java.util.*; public class TestJavaCollection4{ public static void main(String args[]){ Stack<String> stack = new Stack<String>(); stack.push("Ayush"); stack.push("Garvit"); stack.push("Amit"); stack.push("Ashish"); stack.push("Garima"); stack.pop(); Iterator<String> itr=stack.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output: Ayush Garvit Amit Ashish Stack
  • 23. HashSet • to create a collection that uses a hash table for storage. • It inherits the AbstractSet class and implements Set interface. • It stores the elements by using a mechanism called hashing. • It contains unique elements only. • It allows null value. • HashSet class is non synchronized. • It doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode. • It is the best approach for search operations.
  • 24. Difference between List and Set • A list can contain duplicate elements whereas Set contains unique elements only.
  • 25. HashSet example ignoring duplicate elements import java.util.*; class HashSet2{ public static void main(String args[]){ //Creating HashSet and adding elements HashSet<String> set=new HashSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); //Traversing elements Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Ajay Vijay Ravi
  • 26. Java Collections – Map • A Map is an object that maps keys to values. • A map cannot contain duplicate keys. • There are three main implementations of Map interfaces: HashMap, TreeMap, and LinkedHashMap. • HashMap: it makes no guarantees concerning the order of iteration • TreeMap: It stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashMap. • LinkedHashMap: It orders its elements based on the order in which they were inserted into the set (insertion-order).
  • 27. HashMap • HashMap is a Map based collection class that is used for storing Key & value pairs, • it is denoted as HashMap<Key, Value> or HashMap<K, V>. • This class makes no guarantees as to the order of the map. • It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).
  • 28. HashMap • It is not an ordered collection • which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. • It does not sort the stored keys and Values. • to import java.util.HashMap or its super class in order to use the HashMap class and methods.
  • 29. import java.util.*; public class HashMapExample1{ public static void main(String args[]){ HashMap<Integer,String> map=new HashMap<Integer,St ring>();//Creating HashMap map.put(1,"Mango"); //Put elements in Map map.put(2,"Apple"); map.put(3,"Banana"); map.put(4,"Grapes"); System.out.println("Iterating Hashmap..."); for(Map.Entry m : map.entrySet()){ System.out.println(m.getKey()+" "+m.getValue()); } } }
  • 30. import java.util.ArrayList; class Main { public static void main(String[] args) { // create an array list to store Integer data ArrayList<Integer> list1 = new ArrayList<>(); list1.add(4); list1.add(5); System.out.println("ArrayList of Integer: " + list1); // creates an array list to store String data ArrayList<String> list2 = new ArrayList<>(); list2.add("Four"); list2.add("Five"); System.out.println("ArrayList of String: " + list2); // creates an array list to store Double data ArrayList<Double> list3 = new ArrayList<>(); list3.add(4.5); list3.add(6.5); System.out.println("ArrayList of Double: " + list3); } } Output ArrayList of Integer: [4, 5] ArrayList of String: [Four, Five] ArrayList of Double: [4.5, 6.5]
  • 31. • we have used the same ArrayList class to store elements of Integer, String, and Double types. This is possible because of Java Generics. • Here, notice the line, • ArrayList<Integer> list1 = new ArrayList<>(); We have used Integer inside the angle brackets, <>. The angle bracket, <> is known as the type parameter in generics. • The type parameter is used to specify the type of objects (data) that the generics class or method works on.