java unit 4 pdf - about java collections

aapalaks 65 views 18 slides Jul 25, 2024
Slide 1
Slide 1 of 18
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18

About This Presentation

AKTU syllabus java unit 4


Slide Content

CollectioninJava
Acollection inJava isaframeworkthatprovidesanarchitecturetostore
andmanipulate agroupofobjects.
JavaCollectionscanachieve alltheoperations thatyouperformondata
suchassearching,sorting,insertion,manipulation, anddeletion.
KeyPoints:
Collectionsareusedtostore,retrieve,manipulate,and
communicateaggregate data.
Collectionscanholdbothhomogeneousandheterogeneous data.
Theycandynamicallygrowandshrinkinsize.
CollectionFramework inJava
TheCollectionFrameworkprovidesaunifiedarchitecturefor
representingandmanipulating collections.
Allthecollectionsframeworkscontainthefollowing:
Interfaces:Theseareabstractdatatypesthatrepresent
collections.Theinterfacesallowcollectionstobemanipulated
independently ofthedetailsoftheirrepresentation.
1.Collection 3.Set 5.Map
2.List 4.Queue
Implementations:Thesearetheconcreteimplementations ofthe
collectioninterfaces.Essentially, theyarereusabledatastructures.
1ArrayList 3.Linkedlist 5.HashSet
2.TreeSet 4.HashMap 6.TreeMap
Algorithms:Thesearethemethodsthatperformuseful
computations,suchassearchingandsorting,onobjectsthat
Iteratorlnterface
TheIteratorinterfaceprovidesawaytoaccesselementsofacollection
sequentiallywithoutexposingtheunderlyingstructure.
Itispartofthejava.utilpackageandisauniversaliteratorforall
collections.
KeyPoints:
Methods:
booleanhasNext(): Returnstrueiftherearemore
elementstoiterateover.
Enext():Returnsthenextelementintheiteration.
voidremove():Removesthelastelementreturnedby
theiterator(optionaloperation).
t
Usage:
TheIteratorinterfaceisusedtotraversecollectionssuch
asList,Set,andMap.
Itsupportsbothreadandremoveoperations.
wArayListo):
List<String> list=new
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()
{
Stringelement=iterator. next();
System.out, printin(element);

computations, suchassearchingandsorting,onobjectsthat
implementcollectioninterfaces.
AdvantagesofCollectionFramework
Consistent API:Thecollectioninterfaceshaveabasicsetofoperations
(suchasaddingandremoving)thatareextendedbyall
implementations.
ReducesProgramming Effort:Byprovidingusefuldatastructuresand
algorithms,theCollectionsFrameworkreducestheprogrammingeffort.
JavaCollectionsFramework
TheJavaCollectionsFramework isstructuredasaunifiedarchitecture
forrepresentingandmanipulating collections.
Thehierarchy isbroadlydividedintothreemajorgroups:
List,Set,andQueue,whichextendtheCollectioninterface,
Map,which isaseparatehierarchy.
Herearetheimportantpointsforeachcomponent:
CollectionInterface
Therootinterfaceofthecollectionsframework.
CollectionInterface
TheCollectioninterface istherootofthecollectionhierarchy.
Itrepresents agroupofobjectsknownaselements.
TheCollectioninterface ispartofthejava.utilpackage.
KeyPoints:
Methods:
booleanadd(Ee):Ensuresthatthiscollectioncontains
thespecifiedelement.
booleanremove(Objecto):Removesasingleinstance
ofthespecifiedelementfromthiscollection.
intsize():Returnsthenumberofelementsinthis
collection.
booleanisEmpty():Returnstrueifthiscollection
containsnoelements.
booleancontains(0bject o):Returnstrueifthis
collectioncontainsthespecifiedelement.
Iterator<E> iterator(): Returnsaniteratoroverthe

Itprovidescommonmethodsikeadd(),remove(),
size(),clear(),contains(),anditerator()
MapInterface
Representsamappingbetweenakeyandavalue.
DoesnotextendtheCollectioninterface.
Providesmethodstoput,get,removeelementsbased
onakey.
Collection interface MapInterface
ashMap
Aryist nkedashMap
nkedList eeMap
ector t-Hashtabie
Stack
Hashset
nkedkashset
reeSet
PoortyQieae
+-DequeInterface
+-ArrayDeque
+-LinkedistDecue
elementsinthiscollection.
booleanaddAl|(Collection<? extendsE>c):Addsallof
theelementsinthespecifiedcollectiontothis
collection.
voidclear():Removes alloftheelementsfromthis
collection.
Subinterfaces:
1.List 2.Set 3.Queue
Usage:
TheCollectioninterfaceprovidesthebasefunctionality
forallcollections.
Collection<String> collection=newArrayList<>();
collection.add("A");
collection.add("B"):
collection.add("C");
for(Stringelerent
:collection) {
System.out printin(element);
ListInterface
TheListinterfaceextendstheCollectioninterfaceandrepresentsan
BasicOperations
l.boolean add(e) 6.voidadd(intindex,element)

I|method2
list.add("A";
list.add("B";
list.add("C");
for(inti=0;i<list.size(); i++)(
System.out. printin list.get(i);
System.0ut.printin(" Aftermodihcation:+arrayList);
I/Removingelements
arrayList.remove("C");
System.out. printin("Afterremoval:"+arrayList);
/Checking size
System.out.printin("Size ofArrayList:"+arrayList.size():
1/Checking ifArrayListcontainsanelement
System.out. printin("DoesArraylistcontain'A'?"+
arraylist.contains("A");
IteratorvsListiterator
Faature
Iterator Listiterator
/ClearingtheArrayList
arraylist.clear();:
System.out.printin ("Afterclearing:"+arrayList);
Applicable to Collection List
Traversal Direction Forwardonty Bothforwardandbackoard
Obtainingterator
hastiext(
ext()
hesPrevseus()
collectin.iterator()'
Nc
"it.itIterater()
LinkedlList
LinkedList isadoublylinkedlistimplementationoftheListinterface.
ItispartoftheJavaCollectionsFrameworkandisfoundinthejava.util
package.
Previo()
tIndes()
UnlikeArrayList,whichusesadynamicarray,LinkedListusesadoubly
ole

rviousndes()'
Ne
()
No
set(E) No
ArrayList
ArrayListisaresizablearrayimplementation oftheListinterface.
ItispartoftheJavaCollectionsFrameworkandisfoundinthejava.util
package.
Arraylistallowsfordynamicarraysthatcangrowasneeded,
whichmeansitcanchangeitssizeduringruntime.
KeyPoints:
UnlikearraysinJava,ArrayListcangrowandshrinkinsize
dynamically.
Allowsduplicateelements.
Provides fastrandomaccesstoelements.
Initialcapacity is10,butitgrowsautomaticallyaselementsare
added.
KeyPoints:
DoublyLinked:EachelementinaLinkedList isstored inanodethat
containsareferencetothenextandpreviouselements.
DynamicSize:Cangrowandshrinkdynamically.
Allowsduplicateelements.
Efficientforaddingorremovingelementsanywhere inthelist.
SlowerthanArrayListforrandomaccess(get(),asitrequirestraversing
fromtheheadortail.
BasicOperations:(SameasArraylist)
importjava.util.:
publicclassLinkedListExample(
publicstaticvoidmain(Stringl] args){
1/CreateoLinkedList
LinkedList<String> linkedlist=newLinkedList<>):
HAddingelements
linkedList.add("Apple");
linkedList.add("Banana");
linkedList. add("Cherry" );
importjava.util.Vector;
publicclassVectorExample
{
publicstaticvoidmain(String|]args)
{

orderedcollection(alsoknownasasequence).
Theusercanaccesselementsbytheirintegerindex(position inthelist)
andsearchforelementsinthelist.
KeyPoints:
Methods:
2.get(intindex)
3.remove(int index)
4.intsize()
5.booleancontains(e)
set(intindex,element)
8.booleanremove(e)
9.voidclear()
voidadd(intindex,Eelement):Insertsthespecified
elementatthespecifiedposition inthislist.
Eget(intindex):Returnstheelementatthespecified
position inthislist.
Eset(intindex,Eelement):Replaces theelementatthe
specifiedposition inthislistwiththespecifiedelement.
Eremove(intindex):Removestheelementatthe
specifiedposition inthislist.
intindexOf(objecto):Returnstheindexofthefirst
OCcurrenceofthespecifiedelementinthislist.
Listiterator<E> listlterator(): Returnsalistiteratorover
theelementsinthislist.
Implementations:
1.ArrayList 2.LinkedList 3.Vector 4.Stack
Usage:
TheListinterfaceallowsfororderedcollectionsthatcan
containduplicateelements.
List<String> list=newArrayList<):
I/List<integer>numbers=Arrays.asList(5.
2.8.13):method 1
importjava.util."
publicclassArrayListExample
{
publicstaticvoidmain(String]args){
7/CreatingonAraylist
List<String>arrayList=newArrayList<>();
1/Addingelements
arrayList.add("A"):
arraylist.add("B"):
arrayList.add("C");
arrayList.add("D");
HAccessingelements
System.out. printin("Element atindex2:"+arrayList.get(2));
iterotingeiements
for(Stringelement:arrayList) {
System.out.printin(element);
/Modifyingelements
arrayList.set(1, "E");

linkedList.set(1,"Orange"); 1/Modifyelement
linkedList.add(2, "Grape");//Addanelement
linkedList.remove("Apple"); //Removeelement
WCheckif"Banana"ispresent
booleancontainsBanana =linkedList.contains(" Banana");
System.out.printin("DoesLinkedListcontain'Banana'?"+
containsBanana);
System.out, printin("Printforwardorderelement"):
Listiterator<String> iterator=linkedList.listiterator():
while(iterator.hasNext() (
System.out,printin(iterator.next());
Vector<String> vector=newVector<>);
vector.add("A");IAddingelements
vector.add("B");
vector.add("C");
IAccessingelements
System.out printin("Elementatindex1:"+vector.get(1);
1/Removingelement
vector.remove(2);
/Sizeofvector
System.out.printin("Sizeofvector:"+vector.size):
System.out, printin("Printreverseorderelement");
while(iterator.hasPrevious()
System.out.printin(iterator.previous():
Arraylist(Collection<? extendsE>c)
Createsalistcontainingtheelementsofthespecifiedcollection,inthe
ordertheyarereturnedbythecollection's iterator.
ItissameForLinked List
istcStringoviciogi ictArravs
aslistA
C
Stack
StackisasubelassofVectorthatimplementsalast-in, first-out (LIFO)
stackofobjects.
Methods:
push(Eitem):Pushesanitemontothetopofthestack.
pop():Removestheobjectatthetopofthestackandreturnsit.
peek():Looksattheobjectatthetopofthestackwithout
removing
it.
isEmpty():Checksifthestackisempty.

List<Stringexistinglist =Arrays.asList("A","B","C");
Arraylist<String> list=newArrayList<>(existingList);
System.out,printin(list)://Output:(A, B,C]
LinkedList(Collection<? extendsE>)
List<String>arraylist=newArrayListo();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
1/CreateoLinkedistusingtheArrayListelerments
LinkedList<String> linkedlist=newLinkedList<>(arrayList);:
import java.util.Stack;
publicclassStackExample
publicstaticvoidmain(String]args)
{
Stack<String> stack=newStacko);
1IPushingelements
stackpush("A");
stackpush-B");
stack.push("C");
IPeekingthetopelement
System.out. printin("Topelement:"+stack.peek());

LinkedListvsArrayList
LinkedListprovidesmethods likeaddFirst,addLast,getFirst,getLast,
removeFirst,removelast,offerFirst,offerlast,peekFirst,peeklast,
pollfirst,pollLast,descendingiterator forefficient insertion,removal,
andtraversaloperationsfrombothends.
ArrayList isoptimizedforrandomaccessandefficientelement
insertion/removal inthemiddle.
Choosingbetweenthemdependsontheusecase:
UseLinkedListforfrequentinsertions/removals atbothendsor
sequentialtraversal.
UseArrayListforscenariosrequiringrandomaccessorfaster
accessbyindex.
Vector
Vector isapartoftheJavaCollectionsFrameworkandimplementsa
growablearrayofobjects.
Itissynchronized,makingitthread-safe,butcanhaveperformance
overheadduetosynchronization.
Methods:
add(e):Addsanelementtotheendofthevector.
get(intindex):Returnstheelementatthespecifiedposition.
remove(intindex):Removestheelementatthespecifiedposition.
size():Returnsthenumberofelementsinthevector.
System.out, printin("Poppedelement:"+stack.pop):
/Checking ifstockisempty
System.out. printin("Is stackempty?"+stack.isEmpty0):
QueueInterface
Queueisacollectiondesigned forholdingelementspriortoprocessing.
ittypicallyorderselementsinaFIFO(first-in, first-out)manner.
Implementations includeLinkedListandPriorityQueue.
Methods:
add(e):Insertsthespecifiedelementintothequeue(throwsan
exception ifitfails).
offer(e):Insertsthespecifiedelementintothequeue(returns
falseifitfails).
remove():Retrievesandremovestheheadofthequeue(throws
NoSuchElementExceptionanexception ifthequeueisempty).
poll():Rtrievesandremovestheheadofthequeue(returnsnul
ifthequeueisempty).
peek():Retrieves,butdoesnotremove,theheadofthequeue
(returnsnull ifthequeueisempty).

importjava.util.LinkedList;
importjava.util.Queue;
public classQueueExample(
publicstaticvoidmain(String|]args){
Queue<String>queue=newLinkedList<>():
IAddingelements
queue.add("A");
queue.add("B");
queue.add("C");
1/Peekingtheheodelement
System.out. printin("Headelement:"+queue.peek()):
1/inkedHashSetxample
Set<String> linkedHashSet =newLinkedHashSet<>();
linkedHashSet.add("B");
linkedHashSet.add ("A");
linkedHashSet. add("C");
System.out. printin("LinkedHashSet:"+linkedHashSet): /
1TreeSetexomple
Set<String treeSet=newTreeSeto);
treeSet.add("B"):
treeSet.add("A");
treeSet.add('C"):
System.out,prhtin("TreeSet:"+treeSet);/ABC
BAC
1IPollingelements
System.out. printin("Polledelement:"+queue.poll()):
1/Checkingthesize
System.out.printin("Size ofqueue:"+queue.size();
HashSet:Fostestforbasicoperotions, noguaranteedorder.
LinkedHashSet: Maintoins insertionorder,slowerthonHashSet.
TreeSet: Maintainselements insortedorder,slowerthanHashSetondLinkedHoshSet.
MapInterface

SetInterface
Represents acollectionthatcannotcontainduplicateelements.
Itmodelsthemathematical setabstraction.
Doesnotguaranteetheorderofelements.
Allowsatmostonenullelement.
Implementations includeHashSet,LinkedHashSet,andTreeSet.
HashSet
ImplementstheSetinterfaceusingahashtable.Itdoesnotguarantee
theorderofelements.
Offersconstant-timeperformanceforbasicoperations(add,remove,
contains).
Doesnotmaintaintheinsertionorder.
Allows nullelements.
Represents acollectionofkeyvaluepairswhereeachkeyisunique.
Mapskeystovaluesanddoesnotallowduplicatekeys.
methodsforadding,accessing,removing,andcheckingforkey-value
pairs.
HashMapClass
ImplementstheMapinterfaceusingahashtable.
Doesnotguaranteetheorderofkey-value pairs.
Providesconstant-time performanceforbasicoperations (put,get,
remove)onaverage.
Allows nullvaluesandonenullkey.
importjava.util.HashMap,
importjava.util.Map;

LinkedHashSet
ExtendsHashSetandmaintains adoubly-linked listofentriesto
preservetheinsertionorder.
Iteratesoverelementsininsertionorder.
SlowerthanHashSetforbasicoperationsduetomaintaining order.
Allowsnullelements.
SortedSetInterface
publicclassHashMapExample
publicstaticvoidmain(Stringl] args)(
Map<String,Integer>hashMap=newHashMap<>();
hashMap.put("One", 1);
hashMap.gt("Two", 2);
hashMap.put("Three", 3);
System.out, printin("HashMap:"+hashMap);
ExtendsSetandmaintainselementsinsortedorderdefinedbytheir
naturalorderingoracomparator.
Providesmethodsforaccessingelementsbytheirposition inthesorted
set.
LinkedHashMap Class
EvtendeHachManandmaintainc incortionorderofkove

Set.
ImplementationsincludeTreeSet.
TreeSet
ImplementsSortedSetusingatreestructure(red-blacktree).
Maintainselementsinsortedorder(ascendingbydefaultorbasedona
customcomparator).
SlowerperformanceforbasicoperationscomparedtoHashSetand
LinkedHashSet.
Doesnotallownullelements.
ExampleOfAllSetsinterface
import java.util.";
publicclassSetExamples {
publicstaticvoidmain(Stringl] args){
1/HashSetexomple
Set<String>hashSet=newHashSet<>();
hashSet.add("B");
hashSet.add("A");
hashSet.add("C");
System.out.printin ("HashSet:"+hashSet);/CBA
ExtendsHashMapandmaintainsinsertionorderofkeys.
Iteratesoverelementsintheordertheywereinserted.
SlowerperformanceforbasicoperationscomparedtoHashMapdueto
maintaining order.
Allowsnullvaluesandonenullkey.
import java.util.LinkedHashMap;
importjava.util.Map;
publicclassLinkedHashMapExample
{
publicstaticvoidmain(Stringl] args){
Map<String, Integer>linkedHashMap=newLinkedHashMap<>():
linkedHashMap.put(One",1);
linkedHashMap.put("Two",2);:
linkedHashMap.put("Three", 3):
System.out.printin("LinkedHashMap:" +linkedHashMap);

HoshMop:Fastestforbasicoperotions, noorderguarantee.
LinkedHashMap: Maintoins insertionorder,inheritsfromHoshMap.
TreeMap: Maintains keysinsortedorder,slowerforbasicoperotions duetosorting.*
HashtableClass
TheHashtableclassinJavaprovidesabasicimplementationofahash
table,whichmapskeystovalues.
ItinheritsfromtheDictionaryclassandimplementstheMapinterface,
makingitsimilartoHashMapbutwithsomedifferences:
Hashtable issynchronized,
Neitherkeysnorvaluescanbenul
importjava.util.Hashtable;
int[]nums=(5,2,8,1,3};
Arrays.sort(nums); //Sortsnumsarrayinascendingorder
SortingCollections
1.Collections.sort():Sorts collectionssuchaslistsusingnatural
ordering (ifelementsimplementComparable)oraspecified
Comparator.
List<String>names=newArrayList<>);
names.add("Alice"
);:
names.add("Bob");
Collectils.sort(names); //Sortsolphobetically (noturalorder)
2.SortingwithComparator:ascending orderuse:
Comparator.naturalOrder() anddescendingorderuse:
Comparator.reverseOrder()
publicclassHashtableExample(
public staticvoidmain(Stringl] args){
/UsingHoshtable
HachtabloStrinalntoGArhachtablo noMHachtahlocs
List<String>names=newArrayList<>();
names.add("Alice"):
names.add("Bob");
Collections.sort(names, Comparator.reverse Order()://Sortsin

System.out.printin("Hashtable:" +hashtable);
IteratorsusedinMapandSet
importjava.util.";
ComparableInterface
Comparable isaninterfaceinthejava.langpackage.
ItdeclaresonemethodcompareTo()whichcomparesthecurrentobject
(this)withanotherobjectofthesametype.
ClassesthatimplementComparablecanbesortedautomatically using
methodslikeArrays.sort()orCollections.sort().
publicclassSetMaplterationExample
{
publicstaticvoidmain(Stringl]args)(
7CreateaHashSet
Set<String> set=newHashSetc>);
HAddelementstotheSet
set.add("Apple");
set.add("Banana");
set.add("Orange");
1/terating overtheSetusingfor-eochloop
System.out. printin("Elements intheSet:");
for(Stringelement:set)(
System.out.printin(element);
publicinterfaceComparable<T>{
publicintcompareTo(T o);
ExampleofComparableInterFace
publicclassStudentimplementsComparable<Student> {
privateStringname;
privateintage;
1HConstructor
publicStudent(Stringname,intage) {
this.name=rtome;
this.ageage;
1/CreateoHashMop
Map<String, Integer>map =newHashMap<o);

publicintcompareTo(Studentother)(
/Comporestudentsbasedonage
returnInteger.compare(this.age, other.age):
7Exompleusogeinmoinmethod
publicstaticvoid main(String
[]args){
List<Student> students=newArrayList<>():
students.add(newStudent("Alice", 20));
students.add(new Student("Bob",18);
students.add(newStudent("Charlie", 22));
/SortingusingCollections.sort)(usesComparable)
Collections.sort(students);
/Printingsortedstudents
System.out.printin ("SortedStudentsbyAge:");
for(Studentstudent:students)(
System.out. printin(student);
PropertiesClass
Properties storeskey-valuepairswherebothkeysandvaluesarestrings.
Itsupportsloadingfromandsavingtofilesusingload()andstore()
methods.
Defaultvaluescanbesetandqueried ifaproperty isnotfoundinthe
currentinstance.
Javasystemproperties (System-getProperties()) areaccessiblethrough
aProperties object.
Exampleusageinvolvessetting,savingtofile,loading,andaccessing
properties.
lItprovidespersistence forapplicationsettingslikedatabase
connectionsandUlconfigurations.
methods:
setProperty(String key,Stringvalue):Setsakey-valuepairinthe
Propertiesobject.
getProperty(String key):Retrievesthevalueassociated witha
specified key.
store(OutputStreamout,Stringcomments):Savesproperties to
anoutputstream,withoptionalcomments.

Comparator Interface
TheComparatorinterface inJavaislocated inthejava.util package.
Itdefinestwomethods:compare(To1,To2)andequals(Object obi).
YoutypicallycreateaninstanceofComparatoreitherasananonymous
class.
Comparator iscommonlyusedwithsortingmethodslike
Collections.sort() forlistsorArrays.sort()forarraystodefinetheorder
inwhichelementsshouldbesorted.
ExampleofComparatorInterface
importjava.util.;
public classStudent
{
private Stringname;
privateintage,
publicStudent(Stringname,intage)(
this.name=name;
this.age=age,
intgetAge()(returnthis.age;)
load(InputStream in):Loadspropertiesfromaninputstream.
stringPropertyNames(): Returnskeyswhereboththekeyand
valuearestrings.
importjava.io.";
importjava.util.;
publicclassStudent(
publicstaticvoidmain(String[] args)(
Propertiesprop=newProperties();
/Settingproperties
prop.setProperty( "database.url", "jdbc:mysql:/localhost:3306/mydb");
prop.setProperty( "database.user","root");
p.setProperty "database.password","password");:prop.
/Sovingproperties toafile
try(OutputStreamoutput=new
FileOutputStream("config. properties") (
prop.store(output, "DatabaseConfiguration");
System.out.printin ("Propertiessavedsuccessfully.");
}catch(1OException e)(
e.printStackTrace():
nuhlic staticunid mainLStrinalLarc)

public staticvoidmain(Stringl] args)
{
List<Student>studentsnewArrayListo:
students.add(new Student("Alice,20):
students.add(newStudent("Bob", 18)):
students.add(new Student(" Charlie",22):
HUsingComporotor tosortbyogeindescendingorder
Comparator<Student> ageComparator anewComparator<Student>()
Override
publicintcompare(Student s1,Students2)(
returninteger.compare(s2 getAge),s1getAge()l: //Descending order
/Loodingpropertiesfromofile
try(InputStream input=newFileinputStream("config properties") {
prop.load(input);
System.out,printin("Propertiesloadedsuccessfully.");
/Displayproperties
prop.forEach(key, value)->(
System.out. printin(key+";"+value);
7SorongsTudentshstusingogeCormporotor
Collections.sort(students,ageComparator);
1/Accessingindividuolproperty
StringdblUrl=prop.getProperty(" database.url");
System.out. printin("DatabaseURL:"+dbUri);