SlideShare a Scribd company logo
2
Most read
3
Most read
7
Most read
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
١
Java Collections
The Java Collections Framework(JCF) is a collection of interfaces
and classes which helps in storing and processing the data efficiently.
This framework has several useful classes which have tons of useful
functions which makes a programmer task super easy. Almost all
collections in Java are derived from the java.util.Collection
interface.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
٢
List:
A List is an ordered Collection (sometimes called a sequence). Lists may
contain duplicate elements. Elements can be inserted or accessed by their
position in the list, using a zero-based index.
It contains methods to insert and delete elements in index basis.
 ArrayList
 LinkedList
 Vector
Methods of Java List Interface
Method Description
void add(int index,Object
element)
It is used to insert element into the invoking list at the index passed in the index.
boolean addAll(int
index,Collection c)
It is used to insert all elements of c into the invoking list at the index passed in the
index.
object get(int index)
It is used to return the object stored at the specified index within the invoking
collection.
object set(int index,Object
element)
It is used to assign element to the location specified by index within the invoking list.
object remove(int index)
It is used to remove the element at position index from the invoking list and return the
deleted element.
int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not an
element of the list, .1 is returned.
int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not an element
of the list, .1 is returned.
List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list. Elements
in the returned list are also referenced by the invoking object.
boolean contains(Object o)
It checks whether the given object o is present in the array list if its there then it
returns true else it returns false.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
٣
ArrayList:
ArrayList is a resizable-array implementation of the List interface. It implements all optional
list operations, and permits all elements, including null. In addition to implementing the List
interface, this class provides methods to manipulate the size of the array that is used internally
to store the list.
Example1:
ArrayList<String> books = new ArrayList<String>();
books.add("Java Book1");
books.add("Java Book2");
books.add("Java Book3");
System.out.println("Books stored in array list are: "+books);
Example2:
ArrayList<String> cities = new ArrayList<String>(){
{
add("Delhi");
add("Agra");
add("Chennai");
}
};
System.out.println("Content of Array list cities:"+cities);
Example3:
ArrayList<String> obj = new ArrayList<String>(
Arrays.asList("Pratap", "Peter", "Harsh"));
System.out.println("Elements are:"+obj);
Example4:
Collections.ncopies:
ArrayList<T> obj = new ArrayList<T>(Collections.nCopies(count, element));
Syntax: count is number of elements and element is the item value
ArrayList<Integer> intlist = new ArrayList<Integer>(
Collections.nCopies(10, 5) );
System.out.println("ArrayList items: "+intlist);
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
۴
Iterator loop:
java.lang.Iterable
A class that implements the Iterable can be used with the new for-loop.
Iterator is used for iterating (looping) various collection classes.
Example:
String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" };
// convert array to list
List<String> lList = Arrays.asList(sArray);
// for loop
System.out.println("#2 for");
for (int i = 0; i < lList.size(); i++) {
System.out.println(lList.get(i));
}
// for loop advance
System.out.println("#3 for advance");
for (String temp : lList) {
System.out.println(temp);
}
//Traversing elements using Iterator loop
Iterator<String> iterator = lList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
۵
Vector:
Like ArrayList it also maintains insertion order but it is rarely used in non-thread environment as it
is synchronized and due to which it gives poor performance in searching, adding, delete and update of
its elements.
1) Vector<Integer> vector = new Vector<Integer>();
2)
// Vector of initial capacity of 2
Vector<String> vec = new Vector<String>(2);
3)
// Vector object = new vector(int initialcapacity, int capacityIncrement)
/* It means upon insertion of 5th element the size would be 10 (4+6) and on 11th
insertion it would be 16(10+6). */
Vector vec= new Vector(4, 6)
/* Adding elements to a vector*/
vec.addElement("Apple");
vec.addElement("Orange");
vec.addElement("Mango");
vec.addElement("Fig");
Method Description
void addElement(Object obj)
Adds the specified component to the end of this vector, increasing
its size by one.
Object elementAt(int index) Returns the component at the specified index.
int capacity()
Returns the current capacity of this vector. capacity means the
length of its internal data array, kept in the field elementData of this
vector. By default vector doubles its capacity
int size() Returns the number of components in this vector.
void setSize(int newSize) Sets the size of this vector.
void trimToSize() Trims the capacity of this vector to be the vector's current size.
void setElementAt(Object obj, int index)
Sets the component at the specified index of this vector to be the
specified object.
Enumeration elements() Returns an enumeration of the components of this vector.
void copyInto(Object[] anArray) Copies the components of this vector into the specified array.
void clear() Removes all of the elements from this vector.
Object[] toArray()
Returns an array containing all of the elements in this vector in the
correct order.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
۶
Differences between ArrayList & Vector:
Vector implements a dynamic array. It is similar to ArrayList, but with some differences:
ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList is fast because it is
non-synchronized.
Vector is slow because it is synchronized i.e. in
multithreading environment, it will hold the other threads
in runnable or non-runnable state until current thread
releases the lock of object.
2) ArrayList uses Iterator interface
to traverse the elements.
Vector uses Enumeration interface to traverse the
elements. But it can use Iterator also.
Traversing Vector elements:
Enumeration en = vec.elements();
System.out.println("nElements are:");
while(en.hasMoreElements())
System.out.print(en.nextElement() + " ");
LinkedList:
LinkedList lkl = new LinkedList();
LinkedList<String> lkl =new LinkedList<String>();
The important points about Java LinkedList are:
o Java LinkedList class can contain duplicate elements.
o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because
no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.
o LinkedList is faster than Arraylist In addition and deletion but
in searching Arraylist is faster than LinkedList.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
٧
Set:
A Set is a Collection that cannot contain duplicate elements. There are three main
implementations of Set interface: HashSet, TreeSet, and LinkedHashSet.
 HashSet
 LinkedHashSet
 TreeSet
HashSet:
Java HashSet is used to create a collection that uses a hash table for storage.
The important points about Java HashSet class are:
1) HashSet doesn’t maintain any order, the elements would be returned in any random
order.
2) HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the
old value would be overwritten.
3) HashSet allows null values.
4) HashSet is non-synchronized.
Methods of Java HashSet class:
Method Description
void clear() It is used to remove all of the elements from this set.
boolean contains(Object o) It is used to return true if this set contains the specified element.
boolean add(Object o) It is used to adds the specified element to this set if it is not already present.
boolean isEmpty() It is used to return true if this set contains no elements.
boolean remove(Object o) It is used to remove the specified element from this set if it is present.
Object clone() It is used to return a shallow copy of this HashSet instance: the elements them
Iterator iterator() It is used to return an iterator over the elements in this set.
int size() It is used to return the number of elements in this set.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
٨
Example 1:
HashSet<String> hset = new HashSet<String>();
// Adding elements to the HashSet
hset.add("Apple");
hset.add("Orange");
hset.add("Fig");
//Addition of duplicate elements
hset.add("Apple");
hset.add("Mango");
//Addition of null values
hset.add(null);
//Displaying HashSet elements
System.out.println(hset);
Example 2:
public class Book {
int id, quantity;
String name,author,publisher;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> hset=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
hset.add(b1);
hset.add(b2);
hset.add(b3);
}
}
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
٩
Traversing elements
Iterator<String> itr=hset.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
Or
for(Book tempBook:hset){
System.out.println(tempBook. getId() + " " + tempBook.getName());
}
LinkedHashSet:
LinkedHashSet maintains the insertion order. It keeps elements, in the same sequence in
which they have been added to the Set.
Example:
LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
TreeSet:
The objects of TreeSet class are stored in ascending order.
Example:
LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to hash table
hs.add(b1);
hs.add(b2);
hs.add(b3);
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
١
Map:
A Map is an object that maps keys to values. A map cannot contain duplicate keys.
 HashMap
 TreeMap
 LinkedHashMap
HashMap:
o A HashMap contains values based on the key.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains no order.
Methods of Java HashMap class
Method Description
void clear() It is used to remove all of the mappings from this map.
boolean containsKey(Object
key)
It is used to return true if this map contains a mapping for the specified key.
boolean
containsValue(Object value)
It is used to return true if this map maps one or more keys to the specified
value.
boolean isEmpty() It is used to return true if this map contains no key-value mappings.
Set entrySet() It is used to return a collection view of the mappings contained in this map.
Set keySet() It is used to return a set view of the keys contained in this map.
Object put(Object key, Object
value)
It is used to associate the specified value with the specified key in this map.
int size() It is used to return the number of key-value mappings in this map.
Collection values() It is used to return a collection view of the values contained in this
map.
Example:
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
١
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(101,"Let us C");
map.put(102, "Operating System");
map.put(103, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
Map<Integer,Book> map=new HashMap<Integer,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(1,b1);
map.put(2,b2);
map.put(3,b3);
Traversing map
for(Map.Entry<Integer, Book> myEntry : map.entrySet()){
int key= myEntry.getKey();
Book b= myEntry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
١
TreeMap:
TreeMap is unsynchronized collection class which means it is not suitable for thread-safe
operations until unless synchronized explicitly:
o It contains only unique elements.
o It cannot have null key but can have multiple null values.
o It maintains data in ascending order.
Methods of Java TreeMap class
Method Description
boolean containsKey(Object key) It is used to return true if this map contains a mapping for
the specified key.
boolean containsValue(Object
value)
It is used to return true if this map maps one or more keys
to the specified value.
Object firstKey() It is used to return the first (lowest) key currently in this
sorted map.
Object get(Object key) It is used to return the value to which this map maps the
specified key.
Object lastKey() It is used to return the last (highest) key currently in this
sorted map.
Object remove(Object key) It is used to remove the mapping for this key from this
TreeMap if present.
void putAll(Map map) It is used to copy all of the mappings from the specified
map to this map.
Set entrySet() It is used to return a set view of the mappings contained in
this map.
int size() It is used to return the number of key-value mappings in
this map.
Collection values() It is used to return a collection view of the values contained
in this map.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
١
Example:
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(102,"Let us C");
map.put(103, "Operating System");
map.put(101, "Data Communication and Networking");
System.out.println("Values before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("Values after remove: "+ map);
What is difference between HashMap and TreeMap?
HashMap TreeMap
1) HashMap can contain one null key. TreeMap can not contain any null key.
2) HashMap maintains no order. TreeMap maintains ascending order.
http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ
١
LinkedHashMap
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with
predictable iteration order.
o A LinkedHashMap contains values based on the key.
o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains data in insertion order.
Example:
//Creating map of Books
Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to map
map.put(2,b2);
map.put(1,b1);
map.put(3,b3);
//Traversing map
for(Map.Entry<Integer, Book> entry:map.entrySet()){
int key=entry.getKey();
Book b=entry.getValue();
System.out.println(key+" Details:");
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}

More Related Content

PPT
Java Collections Framework
PPT
Java collection
PPTX
Java - Collections framework
PDF
Collections in Java Notes
PDF
Collections In Java
PDF
Java 8 Stream API. A different way to process collections.
PPTX
Java Foundations: Methods
PPTX
Core java
Java Collections Framework
Java collection
Java - Collections framework
Collections in Java Notes
Collections In Java
Java 8 Stream API. A different way to process collections.
Java Foundations: Methods
Core java

What's hot (20)

PDF
Java Collection framework
PDF
Arrays in Java
PPT
Java collections concept
PPTX
Java Strings
PDF
Java Collections Tutorials
PDF
Collections Api - Java
PDF
Java threads
PDF
Lecture20 vector
PPTX
Collections framework in java
ODP
Java Collections
PPTX
collection framework in java
PDF
Java Linked List Tutorial | Edureka
PPTX
Collections and its types in C# (with examples)
PPT
Java multi threading
PDF
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
PPSX
Collections - Array List
PPTX
Core java complete ppt(note)
PPTX
String, string builder, string buffer
PPT
Java static keyword
Java Collection framework
Arrays in Java
Java collections concept
Java Strings
Java Collections Tutorials
Collections Api - Java
Java threads
Lecture20 vector
Collections framework in java
Java Collections
collection framework in java
Java Linked List Tutorial | Edureka
Collections and its types in C# (with examples)
Java multi threading
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Collections - Array List
Core java complete ppt(note)
String, string builder, string buffer
Java static keyword
Ad

Similar to Java collections (20)

DOC
Advanced core java
PPT
12_-_Collections_Framework
PPTX
Collection Framework-1.pptx
PPTX
collectionsframework210616084411 (1).pptx
PDF
java unit 4 pdf - about java collections
PPTX
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
PPTX
Collections lecture 35 40
PPTX
collection framework.pptx
PPTX
Presentation1
PPTX
LJ_JAVA_FS_Collection.pptx
PDF
5 collection framework
DOCX
ArrayList.docx
PPTX
List interface in collections framework
DOCX
Collection frame work
PDF
Collection framework (completenotes) zeeshan
PPT
Collection Framework.power point presentation.......
DOCX
Java collections notes
PDF
javacollections.pdf
PPTX
oop lecture framework,list,maps,collection
PPT
Advanced core java
12_-_Collections_Framework
Collection Framework-1.pptx
collectionsframework210616084411 (1).pptx
java unit 4 pdf - about java collections
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
Collections lecture 35 40
collection framework.pptx
Presentation1
LJ_JAVA_FS_Collection.pptx
5 collection framework
ArrayList.docx
List interface in collections framework
Collection frame work
Collection framework (completenotes) zeeshan
Collection Framework.power point presentation.......
Java collections notes
javacollections.pdf
oop lecture framework,list,maps,collection
Ad

More from Hamid Ghorbani (16)

PDF
Spring aop
PDF
Spring boot jpa
PDF
Spring mvc
PDF
Payment Tokenization
PDF
Reactjs Basics
PDF
Rest web service
PDF
Java inheritance
PDF
Java I/o streams
PDF
Java Threads
PDF
Java Reflection
PDF
Java Generics
PDF
Java programming basics
PDF
IBM Integeration Bus(IIB) Fundamentals
PDF
ESB Overview
PDF
Spring security configuration
PDF
SOA & ESB in banking systems(Persian language)
Spring aop
Spring boot jpa
Spring mvc
Payment Tokenization
Reactjs Basics
Rest web service
Java inheritance
Java I/o streams
Java Threads
Java Reflection
Java Generics
Java programming basics
IBM Integeration Bus(IIB) Fundamentals
ESB Overview
Spring security configuration
SOA & ESB in banking systems(Persian language)

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
How Creative Agencies Leverage Project Management Software.pdf
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Nekopoi APK 2025 free lastest update
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
AI in Product Development-omnex systems
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
How Creative Agencies Leverage Project Management Software.pdf
ISO 45001 Occupational Health and Safety Management System
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Design an Analysis of Algorithms I-SECS-1021-03
Nekopoi APK 2025 free lastest update
Understanding Forklifts - TECH EHS Solution
Online Work Permit System for Fast Permit Processing
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Odoo POS Development Services by CandidRoot Solutions
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
Digital Strategies for Manufacturing Companies
Softaken Excel to vCard Converter Software.pdf
AI in Product Development-omnex systems
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
CHAPTER 2 - PM Management and IT Context
How to Migrate SBCGlobal Email to Yahoo Easily
How to Choose the Right IT Partner for Your Business in Malaysia

Java collections

  • 1. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ١ Java Collections The Java Collections Framework(JCF) is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy. Almost all collections in Java are derived from the java.util.Collection interface.
  • 2. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ٢ List: A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. It contains methods to insert and delete elements in index basis.  ArrayList  LinkedList  Vector Methods of Java List Interface Method Description void add(int index,Object element) It is used to insert element into the invoking list at the index passed in the index. boolean addAll(int index,Collection c) It is used to insert all elements of c into the invoking list at the index passed in the index. object get(int index) It is used to return the object stored at the specified index within the invoking collection. object set(int index,Object element) It is used to assign element to the location specified by index within the invoking list. object remove(int index) It is used to remove the element at position index from the invoking list and return the deleted element. int indexOf(Object obj) Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned. int lastIndexOf(Object obj) Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned. List subList(int start, int end) Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object. boolean contains(Object o) It checks whether the given object o is present in the array list if its there then it returns true else it returns false.
  • 3. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ٣ ArrayList: ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. Example1: ArrayList<String> books = new ArrayList<String>(); books.add("Java Book1"); books.add("Java Book2"); books.add("Java Book3"); System.out.println("Books stored in array list are: "+books); Example2: ArrayList<String> cities = new ArrayList<String>(){ { add("Delhi"); add("Agra"); add("Chennai"); } }; System.out.println("Content of Array list cities:"+cities); Example3: ArrayList<String> obj = new ArrayList<String>( Arrays.asList("Pratap", "Peter", "Harsh")); System.out.println("Elements are:"+obj); Example4: Collections.ncopies: ArrayList<T> obj = new ArrayList<T>(Collections.nCopies(count, element)); Syntax: count is number of elements and element is the item value ArrayList<Integer> intlist = new ArrayList<Integer>( Collections.nCopies(10, 5) ); System.out.println("ArrayList items: "+intlist);
  • 4. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ۴ Iterator loop: java.lang.Iterable A class that implements the Iterable can be used with the new for-loop. Iterator is used for iterating (looping) various collection classes. Example: String sArray[] = new String[] { "Array 1", "Array 2", "Array 3" }; // convert array to list List<String> lList = Arrays.asList(sArray); // for loop System.out.println("#2 for"); for (int i = 0; i < lList.size(); i++) { System.out.println(lList.get(i)); } // for loop advance System.out.println("#3 for advance"); for (String temp : lList) { System.out.println(temp); } //Traversing elements using Iterator loop Iterator<String> iterator = lList.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); }
  • 5. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ۵ Vector: Like ArrayList it also maintains insertion order but it is rarely used in non-thread environment as it is synchronized and due to which it gives poor performance in searching, adding, delete and update of its elements. 1) Vector<Integer> vector = new Vector<Integer>(); 2) // Vector of initial capacity of 2 Vector<String> vec = new Vector<String>(2); 3) // Vector object = new vector(int initialcapacity, int capacityIncrement) /* It means upon insertion of 5th element the size would be 10 (4+6) and on 11th insertion it would be 16(10+6). */ Vector vec= new Vector(4, 6) /* Adding elements to a vector*/ vec.addElement("Apple"); vec.addElement("Orange"); vec.addElement("Mango"); vec.addElement("Fig"); Method Description void addElement(Object obj) Adds the specified component to the end of this vector, increasing its size by one. Object elementAt(int index) Returns the component at the specified index. int capacity() Returns the current capacity of this vector. capacity means the length of its internal data array, kept in the field elementData of this vector. By default vector doubles its capacity int size() Returns the number of components in this vector. void setSize(int newSize) Sets the size of this vector. void trimToSize() Trims the capacity of this vector to be the vector's current size. void setElementAt(Object obj, int index) Sets the component at the specified index of this vector to be the specified object. Enumeration elements() Returns an enumeration of the components of this vector. void copyInto(Object[] anArray) Copies the components of this vector into the specified array. void clear() Removes all of the elements from this vector. Object[] toArray() Returns an array containing all of the elements in this vector in the correct order.
  • 6. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ۶ Differences between ArrayList & Vector: Vector implements a dynamic array. It is similar to ArrayList, but with some differences: ArrayList Vector 1) ArrayList is not synchronized. Vector is synchronized. 2) ArrayList is fast because it is non-synchronized. Vector is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object. 2) ArrayList uses Iterator interface to traverse the elements. Vector uses Enumeration interface to traverse the elements. But it can use Iterator also. Traversing Vector elements: Enumeration en = vec.elements(); System.out.println("nElements are:"); while(en.hasMoreElements()) System.out.print(en.nextElement() + " "); LinkedList: LinkedList lkl = new LinkedList(); LinkedList<String> lkl =new LinkedList<String>(); The important points about Java LinkedList are: o Java LinkedList class can contain duplicate elements. o Java LinkedList class maintains insertion order. o Java LinkedList class is non synchronized. o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred. o Java LinkedList class can be used as list, stack or queue. o LinkedList is faster than Arraylist In addition and deletion but in searching Arraylist is faster than LinkedList.
  • 7. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ٧ Set: A Set is a Collection that cannot contain duplicate elements. There are three main implementations of Set interface: HashSet, TreeSet, and LinkedHashSet.  HashSet  LinkedHashSet  TreeSet HashSet: Java HashSet is used to create a collection that uses a hash table for storage. The important points about Java HashSet class are: 1) HashSet doesn’t maintain any order, the elements would be returned in any random order. 2) HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten. 3) HashSet allows null values. 4) HashSet is non-synchronized. Methods of Java HashSet class: Method Description void clear() It is used to remove all of the elements from this set. boolean contains(Object o) It is used to return true if this set contains the specified element. boolean add(Object o) It is used to adds the specified element to this set if it is not already present. boolean isEmpty() It is used to return true if this set contains no elements. boolean remove(Object o) It is used to remove the specified element from this set if it is present. Object clone() It is used to return a shallow copy of this HashSet instance: the elements them Iterator iterator() It is used to return an iterator over the elements in this set. int size() It is used to return the number of elements in this set.
  • 8. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ٨ Example 1: HashSet<String> hset = new HashSet<String>(); // Adding elements to the HashSet hset.add("Apple"); hset.add("Orange"); hset.add("Fig"); //Addition of duplicate elements hset.add("Apple"); hset.add("Mango"); //Addition of null values hset.add(null); //Displaying HashSet elements System.out.println(hset); Example 2: public class Book { int id, quantity; String name,author,publisher; public Book(int id, String name, String author, String publisher, int quantity) { this.id = id; this.name = name; this.author = author; this.publisher = publisher; this.quantity = quantity; } } public class HashSetExample { public static void main(String[] args) { HashSet<Book> hset=new HashSet<Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to HashSet hset.add(b1); hset.add(b2); hset.add(b3); } }
  • 9. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ٩ Traversing elements Iterator<String> itr=hset.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } Or for(Book tempBook:hset){ System.out.println(tempBook. getId() + " " + tempBook.getName()); } LinkedHashSet: LinkedHashSet maintains the insertion order. It keeps elements, in the same sequence in which they have been added to the Set. Example: LinkedHashSet<Book> hs=new LinkedHashSet<Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to hash table hs.add(b1); hs.add(b2); hs.add(b3); TreeSet: The objects of TreeSet class are stored in ascending order. Example: LinkedHashSet<Book> hs=new LinkedHashSet<Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to hash table hs.add(b1); hs.add(b2); hs.add(b3);
  • 10. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ١ Map: A Map is an object that maps keys to values. A map cannot contain duplicate keys.  HashMap  TreeMap  LinkedHashMap HashMap: o A HashMap contains values based on the key. o It contains only unique elements. o It may have one null key and multiple null values. o It maintains no order. Methods of Java HashMap class Method Description void clear() It is used to remove all of the mappings from this map. boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key. boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value. boolean isEmpty() It is used to return true if this map contains no key-value mappings. Set entrySet() It is used to return a collection view of the mappings contained in this map. Set keySet() It is used to return a set view of the keys contained in this map. Object put(Object key, Object value) It is used to associate the specified value with the specified key in this map. int size() It is used to return the number of key-value mappings in this map. Collection values() It is used to return a collection view of the values contained in this map. Example:
  • 11. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ١ HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(101,"Let us C"); map.put(102, "Operating System"); map.put(103, "Data Communication and Networking"); System.out.println("Values before remove: "+ map); // Remove value for key 102 map.remove(102); System.out.println("Values after remove: "+ map); Map<Integer,Book> map=new HashMap<Integer,Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to map map.put(1,b1); map.put(2,b2); map.put(3,b3); Traversing map for(Map.Entry<Integer, Book> myEntry : map.entrySet()){ int key= myEntry.getKey(); Book b= myEntry.getValue(); System.out.println(key+" Details:"); System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); }
  • 12. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ١ TreeMap: TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly: o It contains only unique elements. o It cannot have null key but can have multiple null values. o It maintains data in ascending order. Methods of Java TreeMap class Method Description boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key. boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value. Object firstKey() It is used to return the first (lowest) key currently in this sorted map. Object get(Object key) It is used to return the value to which this map maps the specified key. Object lastKey() It is used to return the last (highest) key currently in this sorted map. Object remove(Object key) It is used to remove the mapping for this key from this TreeMap if present. void putAll(Map map) It is used to copy all of the mappings from the specified map to this map. Set entrySet() It is used to return a set view of the mappings contained in this map. int size() It is used to return the number of key-value mappings in this map. Collection values() It is used to return a collection view of the values contained in this map.
  • 13. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ١ Example: Map<Integer, String> map = new TreeMap<Integer, String>(); map.put(102,"Let us C"); map.put(103, "Operating System"); map.put(101, "Data Communication and Networking"); System.out.println("Values before remove: "+ map); // Remove value for key 102 map.remove(102); System.out.println("Values after remove: "+ map); What is difference between HashMap and TreeMap? HashMap TreeMap 1) HashMap can contain one null key. TreeMap can not contain any null key. 2) HashMap maintains no order. TreeMap maintains ascending order.
  • 14. http://ir.linkedin.com/in/ghorbanihamidava CollectionsJ ١ LinkedHashMap Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface, with predictable iteration order. o A LinkedHashMap contains values based on the key. o It contains only unique elements. o It may have one null key and multiple null values. o It maintains data in insertion order. Example: //Creating map of Books Map<Integer,Book> map=new LinkedHashMap<Integer,Book>(); //Creating Books Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8); Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4); Book b3=new Book(103,"Operating System","Galvin","Wiley",6); //Adding Books to map map.put(2,b2); map.put(1,b1); map.put(3,b3); //Traversing map for(Map.Entry<Integer, Book> entry:map.entrySet()){ int key=entry.getKey(); Book b=entry.getValue(); System.out.println(key+" Details:"); System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity); }