The Java Collections Framework provides classes and interfaces that help store and manipulate collections of objects. The main collection interfaces are List, Set, and Map. Lists allow duplicate elements and access by index. Common List implementations are ArrayList and LinkedList. Sets do not allow duplicates. Common Set implementations are HashSet, LinkedHashSet, and TreeSet. Maps store objects in key-value pairs and cannot have duplicate keys. Common Map implementations are HashMap, TreeMap, and LinkedHashMap.
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);
}