SlideShare a Scribd company logo
1 of 14
Download to read offline
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

What's hot

5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
java 8 new features
java 8 new features java 8 new features
java 8 new features Rohit Verma
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps Hitesh-Java
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListMarcus Biel
 

What's hot (20)

Java collection
Java collectionJava collection
Java collection
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
String in java
String in javaString in java
String in java
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedListLinkedList vs Arraylist- an in depth look at java.util.LinkedList
LinkedList vs Arraylist- an in depth look at java.util.LinkedList
 
Java IO
Java IOJava IO
Java IO
 

Similar to Java collections

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptxSoniaKapoor56
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections frameworkRavi Chythanya
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )charan kumar
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanZeeshan Khan
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40bhawna sharma
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & setsRatnaJava
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.pptNaitikChatterjee
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionssuseredfbe9
 
Please and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdfPlease and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdfalicesilverblr
 
Objective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdfObjective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdfaliracreations
 
Linked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdfLinked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdfadityacomputers001
 
Objective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfObjective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfadvancethchnologies
 

Similar to Java collections (20)

Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
Java.util
Java.utilJava.util
Java.util
 
Array list (java platform se 8 )
Array list (java platform se 8 )Array list (java platform se 8 )
Array list (java platform se 8 )
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Collection Framework-1.pptx
Collection Framework-1.pptxCollection Framework-1.pptx
Collection Framework-1.pptx
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
16 containers
16   containers16   containers
16 containers
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
oop lecture framework,list,maps,collection
oop lecture framework,list,maps,collectionoop lecture framework,list,maps,collection
oop lecture framework,list,maps,collection
 
Please and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdfPlease and Thank youObjective The purpose of this exercise is to .pdf
Please and Thank youObjective The purpose of this exercise is to .pdf
 
Objective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdfObjective The purpose of this exercise is to create a Linked List d.pdf
Objective The purpose of this exercise is to create a Linked List d.pdf
 
Linked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdfLinked List Objective The purpose of this exercise is to cr.pdf
Linked List Objective The purpose of this exercise is to cr.pdf
 
Objective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdfObjective The purpose of this exercise is to create a Linke.pdf
Objective The purpose of this exercise is to create a Linke.pdf
 

More from Hamid Ghorbani

More from Hamid Ghorbani (16)

Spring aop
Spring aopSpring aop
Spring aop
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Payment Tokenization
Payment TokenizationPayment Tokenization
Payment Tokenization
 
Reactjs Basics
Reactjs BasicsReactjs Basics
Reactjs Basics
 
Rest web service
Rest web serviceRest web service
Rest web service
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
IBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) FundamentalsIBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) Fundamentals
 
ESB Overview
ESB OverviewESB Overview
ESB Overview
 
Spring security configuration
Spring security configurationSpring security configuration
Spring security configuration
 
SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)
 

Recently uploaded

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 

Recently uploaded (20)

SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 

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); }