SlideShare una empresa de Scribd logo
1 de 23
Collections in Java
Overview
• A Collection is a container that groups similar elements into
an entity.
• Examples would include a list of bank accounts, set of
students, group of telephone numbers.
• The Collections framework in Java offers a unified approach
to store, retrieve and manipulate a group of data
• Java’s Collection framework has an intuitive approach when
compared to other complex frameworks such as C++
Benefits
• Helpful to developers by providing all standard data structures algorithms
to let the developer concentrate more on functionality rather than the
lower level details
• Faster execution: with a range of options available for choice of
implementation. The framework aids in improving the quality and
performance of Java applications.
• Code to interface: Since the collections framework is coded on the
principles of “Code to Interface”, it aids in inter-operability between APIs
that are not directly related.
• Learning Curve: Easy to learn and start using Collections due to the “Code
to Interface” principles.
Core Collections Framework
• The Collection framework forms a suitable
hierarchy:
Collection
Set List Queue
SortedSet
Map
SortedMap
Core Collections Framework
(Cont’d)
• The core Collections framework is very generic in nature and provides a standard
interface to all operations that can be performed.
• For example the root interface Collection is declared as public interface Collection <E>
– E represents a generic object.
• Collection: This interface is pretty much used in declarations and method signatures so
any type of Collections can be passed around.
• Set: A Collection interface that cannot take any duplicate elements.
• List: An ordered Collection interface that allows duplicate elements and provides
object retrieval based on an integer index.
• Queue: Apart from following the FIFO (First In First Out) principles this Collection offers
variety of implementation.
• Map: Supports Collection of key and value pairs. Design does not allow duplicate keys.
• Sorted Set: Ordered version of the set interface.
• Sorted Map: Maintains ascending order of keys.
Operations Supported by
Collection <E> interface
• boolean isEmpty();
• boolean contains (Object element);
• boolean remove (Object element);
• Interface <E> iterator();
• boolean containsAll (Collection <> C);
• boolean addAll (Collection <? extends E> C);
• boolean removeAll (Collection() > C);
c.removeAll (Collections.Singleton(obj);
• boolean retainAll (Collection <?> C);
• void clear();
• Object[ ] toArray();
• <T> T[ ] toArray(T[ ]a);
Iteration
• Two ways to iterate over Collections:
– Iterator
static void loopThrough(Collection col){
for (Iterator <E> iter = col.iterator();iter.hasnext()) {
Object obj=iter.next();
}
}
– For-each
static void loopThrough(Collection col){
for (Object obj: col) {
//access object
}
}
Set
• Set Interface: It offers inherited services from the root
Collection interface with the added functionality of restricting
duplicate elements.
• Implementations:
Set
HashSet TreeSet LinkedHashSet
Example Code
• Adding unique objects to a collection
Collection <String> uniqueString (Collection<String> c)
{
Set<String> uniqueSetStr = new HashSet<String>();
for (String str: c)
{
if(!uniqueStrSet.add(str)){
System.out.println(“Duplicate deleted:”+ str);
}
}
return uniqueStrSet;
Set Implementation
Comparisons
• Idioms for using bulk operations on sets:
• Copy a set when doing bulk operations to retain the original set.
• Example:
Set <String> unionSet = new TreeSet<String>(set1); unionSet.addAll(set2);
HashSet TreeSet Linked HashSet
Storage Type Hash Table Red-Black Tree Hash Table with
a Linked List
Performance Best
performance
Slower than
HashSet
Little costly than
HashSet
Order of
Iteration
No guarantee of
order of
iteration
Order based Orders elements
based on
insertion
List
• In addition to the core services inherited from the root collection interface, the
list interface offers
– Positional access
– Search
– Customized Iteration
– Range-view
• List Implementation
– ArrayList offers better performance compared to Linkedlist.
List
Arraylist Vector Linkedlist
Typical usage of List
• Bulk Operations
– listA.addAll(listB); // append elements.
• Positional access and search
– Eg: To swap elements in a list.
public static<String> void swap(List<String>strList, int k, int l)
{
String strTmp = strList.get(l);
strList.set(k,strList.get(l));
strList.set(l,strTmp);
}
List Iterator
• Customized Iteration: ListIterator
– Offers iteration in both directions, forward and
backward
– Example:
for(ListIterator<String> lIter=strList.listIterator(strList.size());lIter.hasPrevious())
{
String str = lIter.previous();
}
List Operations
• Range-View:
– subList(int from, int to) returns a view portion of
the sublist starting from <from> to <to> exclusive.
Algorithms available for List
• sort: Uses mergesort
• shuffle: Randomly shuffles elements
• reverse: Reverses order of elements
• rotate: Rotates list by specified number
• fill: Overwrites every element with specified element.
• copy: Copies source list into destination.
• binarySearch: Performs search usng binary search.
• indexOfSubList: Returns index of first subList found.
• lastIndexOfSubList: Returns index of the last subList found.
Queue
• In addition to the inherited core services offered by
Collection, queue offers following methods in two flavors:
Purpose Throw
Exception
Return Special
Value
Insert Inserts an elements
to the queue
add(obj) offer(obj)
Remove Remove head of the
queue and return it.
remove() poll()
Examine Return the head of
the queue
element() peek()
Map
• Basic operations:
– Val put (Object key);
– Val get (Object key);
– Val remove (Object key);
– boolean containsKey (Object key);
– boolean containsValue (Object value);
– int size();
– boolean isEmpty();
• Bulk services
– Void putAll(Map<? extends Key, ? extends Val> map);
– void clear();
Map (Cont’d)
• Views
public set<Key> keySet();
public collection<Val> values();
public set<Maps.Entry<Key,Val>> entrySet();
• Examples:
Iteration over a map
for(Map.Entry<?,vtype> elem: map.entrySet())
System.out.print(element.getKey()+”:”+element.getValue());
To find If a map contains another map
If(map1.entrySet().containsAll(Map2.entrySet()))
If two map objects contain same keys
If(map1.keyset().equals(map2.keyset()))
To find out common keys behave two map objects
Set<Ktype> common keys = new Hashset<Ktype>(map1.commonkeys.retainAll(map2.keyset());
Map Implementations
Performance Increases
Map
HashMap TreeMap Linkedlist HashTable
SortedSet
• SortedSet stores elements in ascending order as per the natural ordering or
as defined by a comparator provided at instantiation time.
• Also the iterator and toArray methods iterate and return array in sorted
order.
• Additional Services provided:
– SortedSet <Element> subSet (Element fromElement, Element toElement);
– SortedSet <Element> headSet (Element toElement);
– SortedSet <Element> tailSet (Element fromElement);
– element first();
– element last();
– Comparator <? Super Element> comparator();
SortedMap
• Organizes data in ascending order based on natural ordering of
the keys or a comparator supplied at instantiation time.
• Services provided in addition to Map interface:
– Comparator <? super Key> comparator();
– SortedMap<Key, Value> SubMap(Key from, key to);
– SortedMap<Key, Value> headMap (key to);
– SortedMap<Key, Value> tailMap(key from);
– Key firstKey();
– Key lastKey();
Map: Pitfalls
• ThreadSafety
– The bulk operations like keySet(), values() and
entrySet() return collections that can be modified
automatically when the underlying collection
changes.
ThreadSafety
• Collections by default are not threadsafe
• In order to achieve thread-safety the following utility methods from <collection>
can be employed.
• Encapsulation
– Implementation style, where the access to the collection is only from a thread-safe client
• Synchronization
– Collections.synchronizedList (new LinkedList(…));
• Unmodifiable
– Collections.unmodifiableList(new LinkedList(…));
• Fail-safe iterator
– Using fail-safe iterators makes sure the collection is not modified as it is iterated.

Más contenido relacionado

La actualidad más candente

Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google CollectionsAndré Faria Gomes
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...WebStackAcademy
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)charan kumar
 
Collection advance
Collection advanceCollection advance
Collection advanceAakash Jain
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 

La actualidad más candente (20)

Collections and generics
Collections and genericsCollections and generics
Collections and generics
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 
07 java collection
07 java collection07 java collection
07 java collection
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Java collection
Java collectionJava collection
Java collection
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
Core Java Programming Language (JSE) : Chapter IX - Collections and Generic F...
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
The map interface (the java™ tutorials collections interfaces)
The map interface (the java™ tutorials   collections   interfaces)The map interface (the java™ tutorials   collections   interfaces)
The map interface (the java™ tutorials collections interfaces)
 
Collection advance
Collection advanceCollection advance
Collection advance
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Collection
CollectionCollection
Collection
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 

Similar a Collections

Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Kenji HASUNUMA
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.pptswapnilslide2019
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxhemanth248901
 
Collection framework
Collection frameworkCollection framework
Collection frameworkJainul Musani
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaSandesh Sharma
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template LibraryGauravPatil318
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List Hitesh-Java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 

Similar a Collections (20)

Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2Collections Framework Beginners Guide 2
Collections Framework Beginners Guide 2
 
Best core & advanced java classes in mumbai
Best core & advanced java classes in mumbaiBest core & advanced java classes in mumbai
Best core & advanced java classes in mumbai
 
Collections
CollectionsCollections
Collections
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Topic-G-JavaCollections Framework.ppt
Topic-G-JavaCollections    Framework.pptTopic-G-JavaCollections    Framework.ppt
Topic-G-JavaCollections Framework.ppt
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
 
JavaCollections.ppt
JavaCollections.pptJavaCollections.ppt
JavaCollections.ppt
 
Lists
ListsLists
Lists
 
collectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptxcollectionframework-141116005344-conversion-gate01.pptx
collectionframework-141116005344-conversion-gate01.pptx
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Java collections
Java collectionsJava collections
Java collections
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Core java by a introduction sandesh sharma
Core java by a introduction sandesh sharmaCore java by a introduction sandesh sharma
Core java by a introduction sandesh sharma
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
 
2 b queues
2 b queues2 b queues
2 b queues
 
Collections Training
Collections TrainingCollections Training
Collections Training
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Immutable js reactmeetup_local_ppt
Immutable js reactmeetup_local_pptImmutable js reactmeetup_local_ppt
Immutable js reactmeetup_local_ppt
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 

Más de Rajkattamuri

Github plugin setup in anypointstudio
Github plugin setup in anypointstudioGithub plugin setup in anypointstudio
Github plugin setup in anypointstudioRajkattamuri
 
For each component in mule
For each component in muleFor each component in mule
For each component in muleRajkattamuri
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in muleRajkattamuri
 
File component in mule
File component in muleFile component in mule
File component in muleRajkattamuri
 
Database component in mule
Database component in muleDatabase component in mule
Database component in muleRajkattamuri
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule Rajkattamuri
 
Java Basics in Mule
Java Basics in MuleJava Basics in Mule
Java Basics in MuleRajkattamuri
 
WebServices Basic Overview
WebServices Basic OverviewWebServices Basic Overview
WebServices Basic OverviewRajkattamuri
 
Java For Begineers
Java For BegineersJava For Begineers
Java For BegineersRajkattamuri
 
WebServices Basics
WebServices BasicsWebServices Basics
WebServices BasicsRajkattamuri
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIRajkattamuri
 
Mule esb dataweave
Mule esb dataweaveMule esb dataweave
Mule esb dataweaveRajkattamuri
 

Más de Rajkattamuri (20)

Github plugin setup in anypointstudio
Github plugin setup in anypointstudioGithub plugin setup in anypointstudio
Github plugin setup in anypointstudio
 
For each component in mule
For each component in muleFor each component in mule
For each component in mule
 
Filter expression in mule
Filter expression in muleFilter expression in mule
Filter expression in mule
 
File component in mule
File component in muleFile component in mule
File component in mule
 
Database component in mule
Database component in muleDatabase component in mule
Database component in mule
 
Choice component in mule
Choice component in mule Choice component in mule
Choice component in mule
 
WebServices
WebServicesWebServices
WebServices
 
Java Basics in Mule
Java Basics in MuleJava Basics in Mule
Java Basics in Mule
 
WebServices Basic Overview
WebServices Basic OverviewWebServices Basic Overview
WebServices Basic Overview
 
Java For Begineers
Java For BegineersJava For Begineers
Java For Begineers
 
Java Basics
Java BasicsJava Basics
Java Basics
 
WebServices Basics
WebServices BasicsWebServices Basics
WebServices Basics
 
Core java
Core javaCore java
Core java
 
WebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDIWebServices SOAP WSDL and UDDI
WebServices SOAP WSDL and UDDI
 
Web services soap
Web services soapWeb services soap
Web services soap
 
Web services wsdl
Web services wsdlWeb services wsdl
Web services wsdl
 
Web services uddi
Web services uddiWeb services uddi
Web services uddi
 
Maven
MavenMaven
Maven
 
Mule esb dataweave
Mule esb dataweaveMule esb dataweave
Mule esb dataweave
 
Mule with drools
Mule with drools Mule with drools
Mule with drools
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 

Collections

  • 2. Overview • A Collection is a container that groups similar elements into an entity. • Examples would include a list of bank accounts, set of students, group of telephone numbers. • The Collections framework in Java offers a unified approach to store, retrieve and manipulate a group of data • Java’s Collection framework has an intuitive approach when compared to other complex frameworks such as C++
  • 3. Benefits • Helpful to developers by providing all standard data structures algorithms to let the developer concentrate more on functionality rather than the lower level details • Faster execution: with a range of options available for choice of implementation. The framework aids in improving the quality and performance of Java applications. • Code to interface: Since the collections framework is coded on the principles of “Code to Interface”, it aids in inter-operability between APIs that are not directly related. • Learning Curve: Easy to learn and start using Collections due to the “Code to Interface” principles.
  • 4. Core Collections Framework • The Collection framework forms a suitable hierarchy: Collection Set List Queue SortedSet Map SortedMap
  • 5. Core Collections Framework (Cont’d) • The core Collections framework is very generic in nature and provides a standard interface to all operations that can be performed. • For example the root interface Collection is declared as public interface Collection <E> – E represents a generic object. • Collection: This interface is pretty much used in declarations and method signatures so any type of Collections can be passed around. • Set: A Collection interface that cannot take any duplicate elements. • List: An ordered Collection interface that allows duplicate elements and provides object retrieval based on an integer index. • Queue: Apart from following the FIFO (First In First Out) principles this Collection offers variety of implementation. • Map: Supports Collection of key and value pairs. Design does not allow duplicate keys. • Sorted Set: Ordered version of the set interface. • Sorted Map: Maintains ascending order of keys.
  • 6. Operations Supported by Collection <E> interface • boolean isEmpty(); • boolean contains (Object element); • boolean remove (Object element); • Interface <E> iterator(); • boolean containsAll (Collection <> C); • boolean addAll (Collection <? extends E> C); • boolean removeAll (Collection() > C); c.removeAll (Collections.Singleton(obj); • boolean retainAll (Collection <?> C); • void clear(); • Object[ ] toArray(); • <T> T[ ] toArray(T[ ]a);
  • 7. Iteration • Two ways to iterate over Collections: – Iterator static void loopThrough(Collection col){ for (Iterator <E> iter = col.iterator();iter.hasnext()) { Object obj=iter.next(); } } – For-each static void loopThrough(Collection col){ for (Object obj: col) { //access object } }
  • 8. Set • Set Interface: It offers inherited services from the root Collection interface with the added functionality of restricting duplicate elements. • Implementations: Set HashSet TreeSet LinkedHashSet
  • 9. Example Code • Adding unique objects to a collection Collection <String> uniqueString (Collection<String> c) { Set<String> uniqueSetStr = new HashSet<String>(); for (String str: c) { if(!uniqueStrSet.add(str)){ System.out.println(“Duplicate deleted:”+ str); } } return uniqueStrSet;
  • 10. Set Implementation Comparisons • Idioms for using bulk operations on sets: • Copy a set when doing bulk operations to retain the original set. • Example: Set <String> unionSet = new TreeSet<String>(set1); unionSet.addAll(set2); HashSet TreeSet Linked HashSet Storage Type Hash Table Red-Black Tree Hash Table with a Linked List Performance Best performance Slower than HashSet Little costly than HashSet Order of Iteration No guarantee of order of iteration Order based Orders elements based on insertion
  • 11. List • In addition to the core services inherited from the root collection interface, the list interface offers – Positional access – Search – Customized Iteration – Range-view • List Implementation – ArrayList offers better performance compared to Linkedlist. List Arraylist Vector Linkedlist
  • 12. Typical usage of List • Bulk Operations – listA.addAll(listB); // append elements. • Positional access and search – Eg: To swap elements in a list. public static<String> void swap(List<String>strList, int k, int l) { String strTmp = strList.get(l); strList.set(k,strList.get(l)); strList.set(l,strTmp); }
  • 13. List Iterator • Customized Iteration: ListIterator – Offers iteration in both directions, forward and backward – Example: for(ListIterator<String> lIter=strList.listIterator(strList.size());lIter.hasPrevious()) { String str = lIter.previous(); }
  • 14. List Operations • Range-View: – subList(int from, int to) returns a view portion of the sublist starting from <from> to <to> exclusive.
  • 15. Algorithms available for List • sort: Uses mergesort • shuffle: Randomly shuffles elements • reverse: Reverses order of elements • rotate: Rotates list by specified number • fill: Overwrites every element with specified element. • copy: Copies source list into destination. • binarySearch: Performs search usng binary search. • indexOfSubList: Returns index of first subList found. • lastIndexOfSubList: Returns index of the last subList found.
  • 16. Queue • In addition to the inherited core services offered by Collection, queue offers following methods in two flavors: Purpose Throw Exception Return Special Value Insert Inserts an elements to the queue add(obj) offer(obj) Remove Remove head of the queue and return it. remove() poll() Examine Return the head of the queue element() peek()
  • 17. Map • Basic operations: – Val put (Object key); – Val get (Object key); – Val remove (Object key); – boolean containsKey (Object key); – boolean containsValue (Object value); – int size(); – boolean isEmpty(); • Bulk services – Void putAll(Map<? extends Key, ? extends Val> map); – void clear();
  • 18. Map (Cont’d) • Views public set<Key> keySet(); public collection<Val> values(); public set<Maps.Entry<Key,Val>> entrySet(); • Examples: Iteration over a map for(Map.Entry<?,vtype> elem: map.entrySet()) System.out.print(element.getKey()+”:”+element.getValue()); To find If a map contains another map If(map1.entrySet().containsAll(Map2.entrySet())) If two map objects contain same keys If(map1.keyset().equals(map2.keyset())) To find out common keys behave two map objects Set<Ktype> common keys = new Hashset<Ktype>(map1.commonkeys.retainAll(map2.keyset());
  • 20. SortedSet • SortedSet stores elements in ascending order as per the natural ordering or as defined by a comparator provided at instantiation time. • Also the iterator and toArray methods iterate and return array in sorted order. • Additional Services provided: – SortedSet <Element> subSet (Element fromElement, Element toElement); – SortedSet <Element> headSet (Element toElement); – SortedSet <Element> tailSet (Element fromElement); – element first(); – element last(); – Comparator <? Super Element> comparator();
  • 21. SortedMap • Organizes data in ascending order based on natural ordering of the keys or a comparator supplied at instantiation time. • Services provided in addition to Map interface: – Comparator <? super Key> comparator(); – SortedMap<Key, Value> SubMap(Key from, key to); – SortedMap<Key, Value> headMap (key to); – SortedMap<Key, Value> tailMap(key from); – Key firstKey(); – Key lastKey();
  • 22. Map: Pitfalls • ThreadSafety – The bulk operations like keySet(), values() and entrySet() return collections that can be modified automatically when the underlying collection changes.
  • 23. ThreadSafety • Collections by default are not threadsafe • In order to achieve thread-safety the following utility methods from <collection> can be employed. • Encapsulation – Implementation style, where the access to the collection is only from a thread-safe client • Synchronization – Collections.synchronizedList (new LinkedList(…)); • Unmodifiable – Collections.unmodifiableList(new LinkedList(…)); • Fail-safe iterator – Using fail-safe iterators makes sure the collection is not modified as it is iterated.