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

Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
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 - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets Hitesh-Java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections frameworkRiccardo Cardin
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection frameworkankitgarg_er
 
Collections in Java
Collections in JavaCollections in Java
Collections in JavaKhasim Cise
 

What's hot (20)

Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Java collection
Java collectionJava collection
Java collection
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
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
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
07 java collection
07 java collection07 java collection
07 java collection
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
sets and maps
 sets and maps sets and maps
sets and maps
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Java interface
Java interfaceJava interface
Java interface
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 

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

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
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
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 

Recently uploaded (20)

EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
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
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 

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