0% found this document useful (0 votes)
375 views77 pages

JAVA Collection Framework

Collections in Java provide a framework for storing and manipulating groups of objects. The framework includes interfaces like Set, List, Queue, and Deque as well as classes like ArrayList, LinkedList, HashSet and TreeSet. It provides a unified architecture with common functionality for tasks like searching, sorting, insertion, manipulation and deletion for any data stored in collections. The Collections framework represents a standardized, optimized way to work with groups of objects in Java programs.

Uploaded by

gunndu klement
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
375 views77 pages

JAVA Collection Framework

Collections in Java provide a framework for storing and manipulating groups of objects. The framework includes interfaces like Set, List, Queue, and Deque as well as classes like ArrayList, LinkedList, HashSet and TreeSet. It provides a unified architecture with common functionality for tasks like searching, sorting, insertion, manipulation and deletion for any data stored in collections. The Collections framework represents a standardized, optimized way to work with groups of objects in Java programs.

Uploaded by

gunndu klement
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 77

Collections in Java

Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is Collection in java

Collection represents a single unit of objects i.e. a group.

What is framework in java

 provides readymade architecture.


 represents set of classes and interface.
 is optional.

What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

 Interfaces and its implementations i.e. classes


 Algorithm

 What are the two ways to iterate the elements of a collection ?


 What is the difference between ArrayList and LinkedList classes in collection
framework?
 What is the difference between ArrayList and Vector classes in collection
framework?
 What is the difference between HashSet and HashMap classes in collection
framework?
 What is the difference between HashMap and Hashtable class?
 What is the difference between Iterator and Enumeration interface in collection
framework?
 How can we sort the elements of an object. What is the difference between
Comparable and Comparator interfaces?
 What does the hashcode() method ?
 What is the difference between java collection and java collections ?

1
Hierarchy of Collection Framework

Let us see the hierarchy of collection framework.The java.util package contains all the
classes and interfaces for Collection framework.

2
Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description


1 public boolean add(Object element) is used to insert an element in this collection.
2 public boolean addAll(Collection c) is used to insert the specified collection elements
in the invoking collection.
3 public boolean remove(Object element) is used to delete an element from this collection.
4 public boolean removeAll(Collection c) is used to delete all the elements of specified
collection from the invoking collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking
collection except the specified collection.
6 public int size() return the total number of elements in the
collection.
7 public void clear() removes the total no of element from the
collection.
8 public boolean contains(Object element) is used to search an element.
9 public boolean containsAll(Collection c) is used to search the specified collection in this
collection.
10 public Iterator iterator() returns an iterator.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.
14 public int hashCode() returns the hashcode number for collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

 public boolean hasNext() it returns true if iterator has more elements.


 public object next() it returns the element and moves the cursor pointer to the next
element.
 public void remove() it removes the last elements returned by the iterator. It is rarely
used.

3
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.

The important points about Java ArrayList class are:

 Java ArrayList class can contain duplicate elements.


 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index basis.
 In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.

Hierarchy of ArrayList class

As shown in above diagram, Java ArrayList class extends AbstractList class which
implements List interface. The List interface extends Collection and Iterable interfaces in
hierarchical order.

ArrayList class declaration

Let's see the declaration for java.util.ArrayList class.

 public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess,


Cloneable, Serializable

4
 Constructors of Java ArrayList

Constructor Description
ArrayList() It is used to build an empty array list.

ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the
collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

 Methods of Java ArrayList

Method Description
void add(int index, Object element) It is used to insert the specified element at the specified
position index in a list.
boolean addAll(Collection c) It is used to append all of the elements in the specified
collection to the end of this list, in the order that they are
returned by the specified collection's iterator.
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.
Object[] toArray() It is used to return an array containing all of the elements in
this list in the correct order.
Object[] toArray(Object[] a) It is used to return an array containing all of the elements in
this list in the correct order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, Collection c) It is used to insert all of the elements in the specified
collection into this list, starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.
int indexOf(Object o) It is used to return the index in this list of the first
occurrence of the specified element, or -1 if the List does
not contain this element.
void trimToSize() It is used to trim the capacity of this ArrayList instance to be
the list's current size.

Java Non-generic Vs Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in collection. Now it is
type safe so typecasting is not required at run time.

5
Let's see the old non-generic example of creating java collection.

 ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

 ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

In generic collection, we specify the type in angular braces. Now ArrayList is forced to have
only specified type of objects in it. If you try to add another type of object, it gives compile
time error.

Java ArrayList Example

1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Two ways to iterate the elements of collection in java

There are two ways to traverse collection elements:

 By Iterator interface.
 By for-each loop.

In the above example, we have seen traversing ArrayList by Iterator. Let's see the example to
traverse ArrayList elements using for-each loop.

6
Iterating Collection through for-each loop

1. import java.util.*;
2. class TestCollection2{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. for(String obj:al)
10. System.out.println(obj);
11. }
12. }

User-defined class objects in Java ArrayList

Example where we are storing Student class object in array list.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

1. import java.util.*;
2. public class TestCollection3{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. al.add(s1);//adding Student class object
11. al.add(s2);
12. al.add(s3);
13. //Getting Iterator
14. Iterator itr=al.iterator();
15. //traversing elements of ArrayList object
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age); }}}

7
 Example of addAll(Collection c) method

1. import java.util.*;
2. class TestCollection4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Sonoo");
10. al2.add("Hanumat");
11. al.addAll(al2);//adding second list in first list
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }

 Example of removeAll() method

1. import java.util.*;
2. class TestCollection5{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.removeAll(al2);
12. System.out.println("iterating the elements after removing the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17.
18. }
19. }

O/P :

iterating the elements after removing the elements of al2...


Vijay
Ajay

8
 Example of retainAll() method

1. import java.util.*;
2. class TestCollection6{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. al2.add("Ravi");
10. al2.add("Hanumat");
11. al.retainAll(al2);
12. System.out.println("iterating the elements after retaining the elements of al2...");
13. Iterator itr=al.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. }
18. }

 ArrayList example where we are adding books to list and printing all the books.

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. } }
13. public class ArrayListExample {
14. public static void main(String[] args) {
15. //Creating list of Books
16. List<Book> list=new ArrayList<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to list
22. list.add(b1);
23. list.add(b2);
24. list.add(b3);
25. //Traversing list
26. for(Book b:list){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
28. }
29. }
30. }

9
Java LinkedList class

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

 Java LinkedList class can contain duplicate elements.


 Java LinkedList class maintains insertion order.
 Java LinkedList class is non synchronized.
 In Java LinkedList class, manipulation is fast because no shifting needs to be
occurred.
 Java LinkedList class can be used as list, stack or queue.

 Hierarchy of LinkedList class

As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.

10
 Doubly Linked List

In case of doubly linked list, we can add or remove elements from both side.

LinkedList class declaration

Declaration for java.util.LinkedList class.

 public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque


<E>, Cloneable, Serializable

 Constructors of Java LinkedList

Constructor Description
LinkedList() It is used to construct an empty list.
LinkedList(Collection c) It is used to construct a list containing the elements of the specified
collection, in the order they are returned by the collection's iterator.

 Methods of Java LinkedList

Method Description
void add(int index, Object It is used to insert the specified element at the specified position index
element) in a list.
void addFirst(Object o) It is used to insert the given element at the beginning of a list.
void addLast(Object o) It is used to append the given element to the end of a list.
int size() It is used to return the number of elements in a list
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurence of the specified element in a
list.
Object getFirst() It is used to return the first element in a list.
Object getLast() It is used to return the last element in a list.
int indexOf(Object o) It is used to return the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain any element.
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain any element.

11
 Java LinkedList Example

1. import java.util.*;
2. public class TestCollection7{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

 Java LinkedList Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }

12
 Difference between ArrayList and LinkedList

ArrayList and LinkedList both implements List interface and maintains insertion order. Both
are non synchronized classes.

But there are many differences between ArrayList and LinkedList classes that are given
below.

ArrayList LinkedList
1) ArrayList internally uses dynamic array to LinkedList internally uses doubly linked list to
store the elements. store the elements.
2) Manipulation with ArrayList is slow because it Manipulation with LinkedList is faster than
internally uses array. If any element is removed ArrayList because it uses doubly linked list so no
from the array, all the bits are shifted in memory. bit shifting is required in memory.
3) ArrayList class can act as a list only because it LinkedList class can act as a list and queue both
implements List only. because it implements List and Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

Example of ArrayList and LinkedList in Java

1. import java.util.*;
2. class TestArrayLinked{
3. public static void main(String args[]){

4. List<String> al=new ArrayList<String>();//creating arraylist


5. al.add("Ravi");//adding object in arraylist
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");

9. List<String> al2=new LinkedList<String>();//creating linkedlist


10. al2.add("James");//adding object in linkedlist
11. al2.add("Serena");
12. al2.add("Swati");
13. al2.add("Junaid");
14.
15. System.out.println("arraylist: "+al);
16. System.out.println("linkedlist: "+al2);
17. }
18. }
O/P :

arraylist: [Ravi,Vijay,Ravi,Ajay]
linkedlist: [James,Serena,Swati,Junaid]

13
Java List Interface
List Interface is the subinterface of Collection.It contains methods to insert and delete
elements in index basis.It is a factory of ListIterator interface.

 List Interface declaration

public interface List<E> extends Collection<E>

 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.

ListIterator listIterator() It is used to return an iterator to the start of the invoking list.

ListIterator listIterator(int index) It is used to return an iterator to the invoking list that begins
at the specified index.

 Java List Example

1. import java.util.*;
2. public class ListExample{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("Element at 2nd position: "+al.get(2));
10. for(String s:al){
11. System.out.println(s);
12. }
13. }
14. }
14
 Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction.

 ListIterator Interface declaration

public interface ListIterator<E> extends Iterator<E>

 Methods of Java ListIterator Interface:

Method Description

boolean hasNext() This method return true if the list iterator has more elements when
traversing the list in the forward direction.

Object next() This method return the next element in the list and advances the cursor
position.

boolean hasPrevious() This method return true if this list iterator has more elements when
traversing the list in the reverse direction.

Object previous() This method return the previous element in the list and moves the cursor
position backwards.

Example of ListIterator Interface

1. import java.util.*;
2. public class TestCollection8{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. al.add("Amit");
6. al.add("Vijay");
7. al.add("Kumar");
8. al.add(1,"Sachin");
9. System.out.println("element at 2nd position: "+al.get(2));
10. ListIterator<String> itr=al.listIterator();
11. System.out.println("traversing elements in forward direction...");
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. System.out.println("traversing elements in backward direction...");
16. while(itr.hasPrevious()){
17. System.out.println(itr.previous());
18. } } }

15
Example of ListIterator Interface: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. list.add(b1);
24. list.add(b2);
25. list.add(b3);
26. //Traversing list
27. for(Book b:list){
28. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
29. }
30. }
31. }

O/P:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

16
Java HashSet class
Java HashSet class is used to create a collection that uses a hash table for storage. It inherits
the AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

 HashSet stores the elements by using a mechanism called hashing.


 HashSet contains unique elements only.

 Difference between List and Set

List can contain duplicate elements whereas Set contains unique elements only.

 Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration

Let's see the declaration for java.util.HashSet class.

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,


Serializable

17
 Constructors of Java HashSet class:

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using the elements of the collection c.

HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer value
capacity. The capacity grows automatically as elements are added to the
HashSet.

 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 themselves are not cloned.

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.

18
Java HashSet Example

1. import java.util.*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Java HashSet Example: Book

HashSet example where we are adding books to set and printing all the books.

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. } }
13. public class HashSetExample {
14. public static void main(String[] args) {
15. HashSet<Book> set=new HashSet<Book>();
16. //Creating Books
17. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
18. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
19. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
20. //Adding Books to HashSet
21. set.add(b1);
22. set.add(b2);
23. set.add(b3);
24. //Traversing HashSet
25. for(Book b:set){
26. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
27. } }}

19
Java LinkedHashSet class
Java LinkedHashSet class is a Hash table and Linked list implementation of the set interface.
It inherits HashSet class and implements Set interface.

The important points about Java LinkedHashSet class are:

 Contains unique elements only like HashSet.


 Provides all optional set operations, and permits null elements.
 Maintains insertion order.

 Hierarchy of LinkedHashSet class

The LinkedHashSet class extends HashSet class which implements Set interface. The Set
interface inherits Collection and Iterable interfaces in hierarchical order.

 LinkedHashSet class declaration

Declaration for java.util.LinkedHashSet class.

public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable,


Serializable

20
 Constructors of Java LinkedHashSet class

Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using the elements


of the collection c.

LinkedHashSet(int capacity) It is used initialize the capacity of the linkedhashset to


the given integer value capacity.

LinkedHashSet(int capacity, float fillRatio) It is used to initialize both the capacity and the fill ratio
(also called load capacity) of the hash set from its
argument.

Example of LinkedHashSet class:

1. import java.util.*;
2. class TestCollection10{
3. public static void main(String args[]){
4. LinkedHashSet<String> al=new LinkedHashSet<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

O/P:

Ravi
Vijay
Ajay

21
Java LinkedHashSet Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class LinkedHashSetExample {
15. public static void main(String[] args) {
16. LinkedHashSet<Book> hs=new LinkedHashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to hash table
22. hs.add(b1);
23. hs.add(b2);
24. hs.add(b3);
25. //Traversing hash table
26. for(Book b:hs){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
28. }
29. }
30. }

O/P:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

22
Java TreeSet class
Java TreeSet class implements the Set interface that uses a tree for storage. It inherits
AbstractSet class and implements NavigableSet interface. The objects of TreeSet class are
stored in ascending order.

The important points about Java TreeSet class are:

 Contains unique elements only like HashSet.


 Access and retrieval times are quiet fast.
 Maintains ascending order.

 Hierarchy of TreeSet class

As shown in above diagram, Java TreeSet class implements NavigableSet interface. The
NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in
hierarchical order.

TreeSet class declaration

Declaration for java.util.TreeSet class.

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable,


Serializable

23
 Constructors of Java TreeSet class

Constructor Description
TreeSet() It is used to construct an empty tree set that will be sorted in an
ascending order according to the natural order of the tree set.
TreeSet(Collection c) It is used to build a new tree set that contains the elements of the
collection c.
TreeSet(Comparator comp) It is used to construct an empty tree set that will be sorted according to
given comparator.
TreeSet(SortedSet ss) It is used to build a TreeSet that contains the elements of the given
SortedSet.

 Methods of Java TreeSet class

Method Description
boolean addAll(Collection It is used to add all of the elements in the specified collection to this
c) set.
boolean contains(Object o) It is used to return true if this set contains the specified element.
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.
void add(Object o) It is used to add the specified element to this set if it is not already
present.
void clear() It is used to remove all of the elements from this set.
Object clone() It is used to return a shallow copy of this TreeSet instance.
Object first() It is used to return the first (lowest) element currently in this sorted
set.
Object last() It is used to return the last (highest) element currently in this sorted
set.
int size() It is used to return the number of elements in this set.

24
Java TreeSet Example

1. import java.util.*;
2. class TestCollection11{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. al.add("Ravi");
7. al.add("Vijay");
8. al.add("Ravi");
9. al.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
O/P :

Ajay
Ravi
Vijay

25
Java TreeSet Example: Book

TreeSet example where we are adding books to set and printing all the books. The elements in
TreeSet must be of Comparable type. String and Wrapper classes are Comparable by default.
To add user-defined objects in TreeSet, you need to implement Comparable interface.

1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class TreeSetExample {
24. public static void main(String[] args) {
25. Set<Book> set=new TreeSet<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
30. //Adding Books to TreeSet
31. set.add(b1);
32. set.add(b2);
33. set.add(b3);
34. //Traversing TreeSet
35. for(Book b:set){
36. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
37. }
38. }
39. }

O/P:

101 Data Communications & Networking Forouzan Mc Graw Hill 4


121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6

26
Java Queue Interface
Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first
element is removed first and last element is removed at last.

Queue Interface declaration

public interface Queue<E> extends Collection<E>

 Methods of Java Queue Interface

Method Description

boolean add(object) It is used to insert the specified element into this queue and return true
upon success.

boolean offer(object) It is used to insert the specified element into this queue.

Object remove() It is used to retrieves and removes the head of this queue.

Object poll() It is used to retrieves and removes the head of this queue, or returns null
if this queue is empty.

Object element() It is used to retrieves, but does not remove, the head of this queue.

Object peek() It is used to retrieves, but does not remove, the head of this queue, or
returns null if this queue is empty.

PriorityQueue class

The PriorityQueue class provides the facility of using queue. But it does not orders the
elements in FIFO manner. It inherits AbstractQueue class.

PriorityQueue class declaration

Declaration for java.util.PriorityQueue class.

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

27
Java PriorityQueue Example

1. import java.util.*;
2. class TestCollection12{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit");
6. queue.add("Vijay");
7. queue.add("Karan");
8. queue.add("Jai");
9. queue.add("Rahul");
10. System.out.println("head:"+queue.element());
11. System.out.println("head:"+queue.peek());
12. System.out.println("iterating the queue elements:");
13. Iterator itr=queue.iterator();
14. while(itr.hasNext()){
15. System.out.println(itr.next());
16. }
17. queue.remove();
18. queue.poll();
19. System.out.println("after removing two elements:");
20. Iterator<String> itr2=queue.iterator();
21. while(itr2.hasNext()){
22. System.out.println(itr2.next());
23. }
24. }
25. }

O/P:

head:Amit
head:Amit
Iterating the queue elements:
Amit
Jai
Karan
Vijay
Rahul
After removing two elements:
Karan
Rahul
Vijay

Java PriorityQueue Example: Book

PriorityQueue example where we are adding books to queue and printing all the books. The
elements in PriorityQueue must be of Comparable type. String and Wrapper classes are
Comparable by default. To add user-defined objects in PriorityQueue, you need to implement
Comparable interface.

28
1. import java.util.*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. public int compareTo(Book b) {
14. if(id>b.id){
15. return 1;
16. }else if(id<b.id){
17. return -1;
18. }else{
19. return 0;
20. }
21. }
22. }
23. public class LinkedListExample {
24. public static void main(String[] args) {
25. Queue<Book> queue=new PriorityQueue<Book>();
26. //Creating Books
27. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
28. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
29. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
30. //Adding Books to the queue
31. queue.add(b1);
32. queue.add(b2);
33. queue.add(b3);
34. System.out.println("Traversing the queue elements:");
35. //Traversing queue elements
36. for(Book b:queue){
37. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
38. }
39. queue.remove();
40. System.out.println("After removing one book record:");
41. for(Book b:queue){
42. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
43. }
44. }
45. }
O/P:
Traversing the queue elements:
101 Data Communications & Networking Forouzan Mc Graw Hill 4
233 Operating System Galvin Wiley 6
121 Let us C Yashwant Kanetkar BPB 8
After removing one book record:
121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6

29
Java Deque Interface
Java Deque Interface is a linear collection that supports element insertion and removal at both
ends. Deque is an acronym for "double ended queue".

Deque Interface declaration

public interface Deque<E> extends Queue<E>

 Methods of Java Deque Interface

Method Description

boolean add(object) It is used to insert the specified element into this deque and return true upon
success.

boolean offer(object) It is used to insert the specified element into this deque.

Object remove() It is used to retrieves and removes the head of this deque.

Object poll() It is used to retrieves and removes the head of this deque, or returns null if
this deque is empty.

Object element() It is used to retrieves, but does not remove, the head of this deque.

Object peek() It is used to retrieves, but does not remove, the head of this deque, or returns
null if this deque is empty.

30
ArrayDeque class
The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.

The important points about ArrayDeque class are:

 Unlike Queue, we can add or remove elements from both sides.


 Null elements are not allowed in the ArrayDeque.
 ArrayDeque is not thread safe, in the absence of external synchronization.
 ArrayDeque has no capacity restrictions.
 ArrayDeque is faster than LinkedList and Stack.

 ArrayDeque Hierarchy

The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the
page.

ArrayDeque class declaration

public class ArrayDeque<E>extends AbstractCollection<E>implements Deque<E>,


Cloneable, Serializable

31
Java ArrayDeque Example

1. import java.util.*;
2. public class ArrayDequeExample {
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Ravi");
7. deque.add("Vijay");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
O/P:
Ravi
Vijay
Ajay

Java ArrayDeque Example: offerFirst() and pollLast()

1. import java.util.*;
2. public class DequeExample {
3. public static void main(String[] args) {
4. Deque<String> deque=new ArrayDeque<String>();
5. deque.offer("arvind");
6. deque.offer("vimal");
7. deque.add("mukul");
8. deque.offerFirst("jai");
9. System.out.println("After offerFirst Traversal...");
10. for(String s:deque){
11. System.out.println(s);
12. }
13. //deque.poll();
14. //deque.pollFirst();//it is same as poll()
15. deque.pollLast();
16. System.out.println("After pollLast() Traversal...");
17. for(String s:deque){
18. System.out.println(s);
19. }
20. } }
O/P:

After offerFirst Traversal...


jai
arvind
vimal
mukul
After pollLast() Traversal...
jai
arvind
vimal
32
Java ArrayDeque Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class ArrayDequeExample {
15. public static void main(String[] args) {
16. Deque<Book> set=new ArrayDeque<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to Deque
22. set.add(b1);
23. set.add(b2);
24. set.add(b3);
25. //Traversing ArrayDeque
26. for(Book b:set){
27. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
28. }
29. }
30. }

O/P:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

33
Java Map Interface
A map contains values on the basis of key i.e. key and value pair. Each key and value pair is
known as an entry. Map contains only unique keys.

Map is useful if you have to search, update or delete elements on the basis of key.

Useful methods of Map interface

Method Description

Object put(Object key, Object value) It is used to insert an entry in this map.

void putAll(Map map) It is used to insert the specified map in this map.

Object remove(Object key) It is used to delete an entry for the specified key.

Object get(Object key) It is used to return the value for the specified key.

boolean containsKey(Object key) It is used to search the specified key from this map.

Set keySet() It is used to return the Set view containing all the keys.

Set entrySet() It is used to return the Set view containing all the keys and
values.

Map.Entry Interface

Entry is the sub interface of Map. So we will be accessed it by Map.Entry name. It provides
methods to get key and value.

Methods of Map.Entry interface

Method Description

Object getKey() It is used to obtain key.

Object getValue() It is used to obtain value.

34
Java Map Example: Generic (New Style)

1. import java.util.*;
2. class MapInterfaceExample{
3. public static void main(String args[]){
4. Map<Integer,String> map=new HashMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(101,"Vijay");
7. map.put(102,"Rahul");
8. for(Map.Entry m:map.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }
O/P:

102 Rahul
100 Amit
101 Vijay

Java Map Example: Non-Generic (Old Style)

1. //Non-generic
2. import java.util.*;
3. public class MapExample1 {
4. public static void main(String[] args) {
5. Map map=new HashMap();
6. //Adding elements to map
7. map.put(1,"Amit");
8. map.put(5,"Rahul");
9. map.put(2,"Jai");
10. map.put(6,"Amit");
11. //Traversing Map
12. Set set=map.entrySet();//Converting to Set so that we can traverse
13. Iterator itr=set.iterator();
14. while(itr.hasNext()){
15. //Converting to Map.Entry so that we can get key and value separately
16. Map.Entry entry=(Map.Entry)itr.next();
17. System.out.println(entry.getKey()+" "+entry.getValue());
18. }
19. }
20. }

O/P:

1 Amit
2 Jai
5 Rahul
6 Amit

35
Java HashMap class

Java HashMap class implements the map interface by using a hashtable. It inherits
AbstractMap class and implements Map interface.

The important points about Java HashMap class are:

 A HashMap contains values based on the key.


 It contains only unique elements.
 It may have one null key and multiple null values.
 It maintains no order.

 Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements
Map interface.

HashMap class declaration

Declaration for java.util.HashMap class.

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,


Cloneable, Serializable

HashMap class Parameters

Parameters for java.util.HashMap class.

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

36
 Constructors of Java HashMap class

Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map m) It is used to initializes the hash map by using the elements of
the given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given
integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and fill ratio of the hash
fillRatio) map by using its arguments.

 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.
Object clone() It is used to return a shallow copy of this HashMap instance:
the keys and values themselves are not cloned.
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.

37
Java HashMap Example

1. import java.util.*;
2. class TestCollection13{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(101,"Vijay");
7. hm.put(102,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }
O/P :

102 Rahul
100 Amit
101 Vijay

Java HashMap Example: remove()

1. import java.util.*;
2. public class HashMapExample {
3. public static void main(String args[]) {
4. // create and populate hash map
5. HashMap<Integer, String> map = new HashMap<Integer, String>();
6. map.put(101,"Let us C");
7. map.put(102, "Operating System");
8. map.put(103, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }

O/P:

Values before remove: {102=Operating System, 103=Data Communication and


Networking, 101=Let us C}
Values after remove: {103=Data Communication and Networking, 101=Let us C}

38
Difference between HashSet and HashMap

HashSet contains only values whereas HashMap contains entry(key and value).

Java HashMap Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new HashMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
33. }
34. }
35. }

[O/P]

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6

39
Java LinkedHashMap class
Java LinkedHashMap class is Hash table and Linked list implementation of the Map interface,
with predictable iteration order. It inherits HashMap class and implements the Map interface.

The important points about Java HashMap class are:

 A LinkedHashMap contains values based on the key.


 It contains only unique elements.
 It may have one null key and multiple null values.
 It is same as HashMap instead maintains insertion order.

 Hierarchy of LinkedHashMap class

LinkedHashMap class declaration

The declaration for java.util.LinkedHashMap class.

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

LinkedHashMap class Parameters

The Parameters for java.util.LinkedHashMap class.

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

40
 Constructors of Java LinkedHashMap class

Constructor Description
LinkedHashMap() It is used to construct a default LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float It is used to initialize both the capacity and the fillRatio.
fillRatio)
LinkedHashMap(Map m) It is used to initialize the LinkedHashMap with the elements
from the given Map class m.

 Methods of Java LinkedHashMap class

Method Description

Object get(Object key) It is used to return the value to which this map maps the specified
key.
void clear() It is used to remove all mappings from this map.

boolean containsKey(Object key) It is used to return true if this map maps one or more keys to the
specified value.

41
Java LinkedHashMap Example

1. import java.util.*;
2. class TestCollection14{
3. public static void main(String args[]){
4.
5. LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
6.
7. hm.put(100,"Amit");
8. hm.put(101,"Vijay");
9. hm.put(102,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
O/P :

100 Amit
101 Vijay
102 Rahul

Java LinkedHashMap Example:remove()

1. import java.util.*;
2. public class LinkedHashMapExample {
3. public static void main(String args[]) {
4. // Create and populate linked hash map
5. Map<Integer, String> map = new LinkedHashMap<Integer, String>();
6. map.put(101,"Let us C");
7. map.put(102, "Operating System");
8. map.put(103, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }

O/P:

Values before remove: {101=Let us C, 102=Operating System, 103=Data


Communication and Networking}
Values after remove: {101=Let us C, 103=Data Communication and Networking}

42
Java LinkedHashMap Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new LinkedHashMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
33. }
34. }
35. }
O/P:

2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8
3 Details:
103 Operating System Galvin Wiley 6

43
Java TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient
means of storing key/value pairs in sorted order.

The important points about Java TreeMap class are:

 A TreeMap contains values based on the key. It implements the NavigableMap


interface and extends AbstractMap class.
 It contains only unique elements.
 It cannot have null key but can have multiple null values.
 It is same as HashMap instead maintains ascending order.

 Hierarchy of LinkedHashMap class

TreeMap class declaration

Tthe declaration for java.util.TreeMap class.

public class TreeMap<K,V> extends AbstractMap<K,V>implements NavigableMap<K,V>,


Cloneable, Serializable

TreeMap class Parameters

Let's see the Parameters for java.util.TreeMap class.

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

44
 Constructors of Java TreeMap class

Constructor Description
TreeMap() It is used to construct an empty tree map that will be sorted
using the natural order of its key.
TreeMap(Comparator comp) It is used to construct an empty tree-based map that will be
sorted using the comparator comp.
TreeMap(Map m) It is used to initialize a tree map with the entries from m, which
will be sorted using the natural order of the keys.
TreeMap(SortedMap sm) It is used to initialize a tree map with the entries from the
SortedMap sm, which will be sorted in the same order as sm.
 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.

45
Java TreeMap Example:

1. import java.util.*;
2. class TestCollection15{
3. public static void main(String args[]){
4. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(102,"Ravi");
7. hm.put(101,"Vijay");
8. hm.put(103,"Rahul");
9. for(Map.Entry m:hm.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue());
11. }
12. }
13. }
O/P :

100 Amit
101 Vijay
102 Ravi
103 Rahul

Java TreeMap Example: remove()

1. import java.util.*;
2. public class TreeMapExample {
3. public static void main(String args[]) {
4. // Create and populate tree map
5. Map<Integer, String> map = new TreeMap<Integer, String>();
6. map.put(102,"Let us C");
7. map.put(103, "Operating System");
8. map.put(101, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }
O/P:

Values before remove: {101=Data Communication and Networking, 102=Let us C,


103=Operating System}
Values after remove: {101=Data Communication and Networking, 103=Operating
System}

 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.

46
Java TreeMap Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class MapExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new TreeMap<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(2,b2);
24. map.put(1,b1);
25. map.put(3,b3);
26.
27. //Traversing map
28. for(Map.Entry<Integer, Book> entry:map.entrySet()){
29. int key=entry.getKey();
30. Book b=entry.getValue();
31. System.out.println(key+" Details:");
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
33. }
34. }
35. }

O/P:

1 Details:
101 Let us C Yashwant Kanetkar BPB 8
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
3 Details:
103 Operating System Galvin Wiley 6

47
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

The important points about Java Hashtable class are:

 A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based on
the key.
 It contains only unique elements.
 It may have not have any null key or value.
 It is synchronized.

Hashtable class declaration

The declaration for java.util.Hashtable class.

public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable,


Serializable

Hashtable class Parameters

The Parameters for java.util.Hashtable class.

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

48
 Constructors of Java Hashtable class

Constructor Description
Hashtable() It is the default constructor of hash table it instantiates the
Hashtable class.
Hashtable(int size) It is used to accept an integer parameter and creates a hash table
that has an initial size specified by integer value size.
Hashtable(int size, float fillRatio) It is used to create a hash table that has an initial size specified
by size and a fill ratio specified by fillRatio.

 Methods of Java Hashtable class

Method Description
void clear() It is used to reset the hash table.
boolean contains(Object value) This method return true if some value equal to the value exist
within the hash table, else return false.
boolean containsValue(Object value) This method return true if some value equal to the value exists
within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exists
within the hash table, else return false.
boolean isEmpty() This method return true if the hash table is empty; returns
false if it contains at least one key.
void rehash() It is used to increase the size of the hash table and rehashes all
of its keys.
Object get(Object key) This method return the object that contains the value
associated with the key.
Object remove(Object key) It is used to remove the key and its value. This method return
the value associated with the key.
int size() This method return the number of entries in the hash table.

49
Java Hashtable Example

1. import java.util.*;
2. class TestCollection16{
3. public static void main(String args[]){
4. Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
5.
6. hm.put(100,"Amit");
7. hm.put(102,"Ravi");
8. hm.put(101,"Vijay");
9. hm.put(103,"Rahul");
10.
11. for(Map.Entry m:hm.entrySet()){
12. System.out.println(m.getKey()+" "+m.getValue());
13. }
14. }
15. }
O/P :

103 Rahul
102 Ravi
101 Vijay
100 Amit

Java Hashtable Example: remove()

1. import java.util.*;
2. public class HashtableExample {
3. public static void main(String args[]) {
4. // create and populate hash table
5. Hashtable<Integer, String> map = new Hashtable<Integer, String>();
6. map.put(102,"Let us C");
7. map.put(103, "Operating System");
8. map.put(101, "Data Communication and Networking");
9. System.out.println("Values before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("Values after remove: "+ map);
13. }
14. }

O/P:

Values before remove: {103=Operating System, 102=Let us C, 101=Data


Communication and Networking}
Values after remove: {103=Operating System, 101=Data Communication and
Networking}

50
Java Hashtable Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class HashtableExample {
15. public static void main(String[] args) {
16. //Creating map of Books
17. Map<Integer,Book> map=new Hashtable<Integer,Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to map
23. map.put(1,b1);
24. map.put(2,b2);
25. map.put(3,b3);
26. //Traversing map
27. for(Map.Entry<Integer, Book> entry:map.entrySet()){
28. int key=entry.getKey();
29. Book b=entry.getValue();
30. System.out.println(key+" Details:");
31. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
32. }
33. }
34. }
O/P:

3 Details:
103 Operating System Galvin Wiley 6
2 Details:
102 Data Communications & Networking Forouzan Mc Graw Hill 4
1 Details:
101 Let us C Yashwant Kanetkar BPB 8

51
 Difference between HashMap and Hashtable

HashMap and Hashtable both are used to store data in key and value form. Both are using
hashing technique to store unique keys.

But there are many differences between HashMap and Hashtable classes that are given below.

HashMap Hashtable
1) HashMap is non synchronized. It is not-thread Hashtable is synchronized. It is thread-
safe and can't be shared between many threads safe and can be shared with many threads.
without proper synchronization code.
2) HashMap allows one null key and multiple null Hashtable doesn't allow any null key or
values. value.
3) HashMap is a new class introduced in JDK 1.2. Hashtable is a legacy class.
4) HashMap is fast. Hashtable is slow.
5) We can make the HashMap as synchronized by Hashtable is internally synchronized and
calling this code can't be unsynchronized.
Map m = Collections.synchronizedMap(hashMap);
6) HashMap is traversed by Iterator. Hashtable is traversed by Enumerator
and Iterator.
7) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.
8) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.

52
Java EnumSet class
Java EnumSet class is the specialized Set implementation for use with enum types. It inherits
AbstractSet class and implements the Set interface.

EnumSet class hierarchy

EnumSet class declaration

The declaration for java.util.EnumSet class.

public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements


Cloneable, Serializable

53
 Methods of Java EnumSet class

Method Description

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set containing all of
allOf(Class<E> elementType) the elements in the specified element type.

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set initialized from
copyOf(Collection<E> c) the specified collection.

static <E extends Enum<E>> EnumSet<E> It is used to create an empty enum set with the
noneOf(Class<E> elementType) specified element type.

static <E extends Enum<E>> EnumSet<E> of(E It is used to create an enum set initially
e) containing the specified element.

static <E extends Enum<E>> EnumSet<E> It is used to create an enum set initially
range(E from, E to) containing the specified elements.

EnumSet<E> clone() It is used to return a copy of this set.

54
Java EnumSet Example

1. import java.util.*;
2. enum days {
3. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

4. }
5. public class EnumSetExample {
6. public static void main(String[] args) {
7. Set<days> set = EnumSet.of(days.TUESDAY, days.WEDNESDAY);
8. // Traversing elements
9. Iterator<days> iter = set.iterator();
10. while (iter.hasNext())
11. System.out.println(iter.next());
12. }
13. }

O/P:

TUESDAY
WEDNESDAY

Java EnumSet Example: allOf() and noneOf()

1. import java.util.*;
2. enum days {
3. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

4. }
5. public class EnumSetExample {
6. public static void main(String[] args) {
7. Set<days> set1 = EnumSet.allOf(days.class);
8. System.out.println("Week Days:"+set1);
9. Set<days> set2 = EnumSet.noneOf(days.class);
10. System.out.println("Week Days:"+set2);
11. }
12. }

O/P:

Week Days:[SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY]
Week Days:[]

55
Java EnumMap class
Java EnumMap class is the specialized Map implementation for enum keys. It inherits Enum
and AbstractMap classes.

EnumMap class hierarchy

EnumMap class declaration

The declaration for java.util.EnumMap class.

public class EnumMap<K extends Enum<K>,V> extends AbstractMap<K,V> implements


Serializable, Cloneable

EnumMap class Parameters

Let's see the Parameters for java.util.EnumMap class.

 K: It is the type of keys maintained by this map.


 V: It is the type of mapped values.

56
 Constructors of Java EnumMap class

Constructor Description

EnumMap(Class<K> keyType) It is used to create an empty enum map with the


specified key type.

EnumMap(EnumMap<K,? extends V> m) It is used to create an enum map with the same key
type as the specified enum map.

EnumMap(Map<K,? extends V> m) It is used to create an enum map initialized from the
specified map.

 Methods of Java EnumMap class

Method Description

void clear() It is used to remove all mappings from this map.

boolean containsKey(Object key) This method return true if this map contains a mapping
for the specified key.

boolean containsValue(Object value) This method return true if this map maps one or more
keys to the specified value.

boolean equals(Object o) It is used to compare the specified object with this map
for equality.

V get(Object key) This method returns the value to which the specified key
is mapped.

V put(K key, V value) It is used to associate the specified value with the
specified key in this map.

V remove(Object key) It is used to remove the mapping for this key.

Collection<V> values() It is used to return a Collection view of the values


contained in this map.

int size() It is used to return the number of key-value mappings in


this map.

57
Java EnumMap Example

1. import java.util.*;
2. public class EnumMapExample {
3. // create an enum
4. public enum Days {
5. Monday, Tuesday, Wednesday, Thursday
6. };
7. public static void main(String[] args) {
8. //create and populate enum map
9. EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);
10. map.put(Days.Monday, "1");
11. map.put(Days.Tuesday, "2");
12. map.put(Days.Wednesday, "3");
13. map.put(Days.Thursday, "4");
14. // print the map
15. for(Map.Entry m:map.entrySet()){
16. System.out.println(m.getKey()+" "+m.getValue());
17. }
18. }
19. }

O/P:

Monday 1
Tuesday 2
Wednesday 3
Thursday 4

58
Java EnumMap Example: Book

1. import java.util.*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. this.id = id;
8. this.name = name;
9. this.author = author;
10. this.publisher = publisher;
11. this.quantity = quantity;
12. }
13. }
14. public class EnumMapExample {
15. // Creating enum
16. public enum Key{
17. One, Two, Three
18. };
19. public static void main(String[] args) {
20. EnumMap<Key, Book> map = new EnumMap<Key, Book>(Key.class);
21. // Creating Books
22. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
23. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hi
ll",4);
24. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
25. // Adding Books to Map
26. map.put(Key.One, b1);
27. map.put(Key.Two, b2);
28. map.put(Key.Three, b3);
29. // Traversing EnumMap
30. for(Map.Entry<Key, Book> entry:map.entrySet()){
31. Book b=entry.getValue();
32. System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
33. }
34. }
35. }

O/P:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

59
Java Collections class
Java collection class is used exclusively with static methods that operate on or return
collections. It inherits Object class.

The important points about Java Collections class are:

 Java Collection class supports the polymorphic algorithms that operate on


collections.
 Java Collection class throws a NullPointerException if the collections or class
objects provided to them are null.

Collections class declaration

The declaration for Java.util.Collections class.

public class Collections extends Object

Methods of Java Collections class

Method Description

static <T> boolean addAll(Collection<? super T> c, It is used to add all of the specified elements
T... elements) to the specified collection.

static <T> Queue<T> asLifoQueue(Deque<T> deque) It is used to return a view of a Deque as a


Last-In-First-Out (LIFO) Queue.

static <T> int binarySearch(List<? extends T> list, T It is used to search the specified list for the
key, Comparator<? super T< c) specified object using the binary search
algorithm.

static <E> List<E> checkedList(List<E> list, It is used to return a dynamically typesafe


Class<E> type) view of the specified list.

static <E> Set<E> checkedSet(Set<E> s, Class<E> It is used to return a dynamically typesafe


type) view of the specified set.

static <E> It is used to return a dynamically typesafe


SortedSet<E>checkedSortedSet(SortedSet<E> s, view of the specified sorted set
Class<E> type)

static void reverse(List<?> list) It is used to reverse the order of the


elements in the specified list.

60
static <T> T max(Collection<? extends T> coll, It is used to return the maximum element of
Comparator<? super T> comp) the given collection, according to the order
induced by the specified comparator.

static <T extends Object & Comparable<? super T>>T It is used to return the minimum element of
min(Collection<? extends T> coll) the given collection, according to the
natural ordering of its elements.

static boolean replaceAll(List list, T oldVal, T It is used to replace all occurrences of one
newVal) specified value in a list with another.

Java Collections Example

1. import java.util.*;
2. public class CollectionsExample {
3. public static void main(String a[]){
4. List<String> list = new ArrayList<String>();
5. list.add("C");
6. list.add("Core Java");
7. list.add("Advance Java");
8. System.out.println("Initial collection value:"+list);
9. Collections.addAll(list, "Servlet","JSP");
10. System.out.println("After adding elements collection value:"+list);
11. String[] strArr = {"C#", ".Net"};
12. Collections.addAll(list, strArr);
13. System.out.println("After adding array collection value:"+list);
14. }
15. }

O/P:

Initial collection value:[C, Core Java, Advance Java]


After adding elements collection value:[C, Core Java, Advance Java, Servlet, JSP]
After adding array collection value:[C, Core Java, Advance Java, Servlet, JSP, C#, .Net]

61
Java Collections Example: max()

1. import java.util.*;
2. public class CollectionsExample {
3. public static void main(String a[]){
4. List<Integer> list = new ArrayList<Integer>();
5. list.add(46);
6. list.add(67);
7. list.add(24);
8. list.add(16);
9. list.add(8);
10. list.add(12);
11. System.out.println("Value of maximum element from the collection: "+Collections.max(
list));
12. }
13. }

O/P:

Value of maximum element from the collection: 67

Java Collections Example: min()

1. import java.util.*;
2. public class CollectionsExample {
3. public static void main(String a[]){
4. List<Integer> list = new ArrayList<Integer>();
5. list.add(46);
6. list.add(67);
7. list.add(24);
8. list.add(16);
9. list.add(8);
10. list.add(12);
11. System.out.println("Value of minimum element from the collection: "+Collections.min(li
st));
12. }
13. }

O/P:

Value of minimum element from the collection: 8

62
Sorting in Collection
We can sort the elements of:

 String objects
 Wrapper class objects
 User-defined class objects

Collections class provides static methods for sorting the elements of collection.If
collection elements are of Set type, we can use TreeSet.But We cannot sort the elements of
List.Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List.List elements must be of
Comparable type.

Note: String class and Wrapper classes implements the Comparable interface.So if you
store the objects of string or wrapper classes, it will be Comparable.

Example of Sorting the elements of List that contains string objects

1. import java.util.*;
2. class TestSort1{
3. public static void main(String args[]){
4.
5. ArrayList<String> al=new ArrayList<String>();
6. al.add("Viru");
7. al.add("Saurav");
8. al.add("Mukesh");
9. al.add("Tahir");
10.
11. Collections.sort(al);
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
O/P :

Mukesh
Saurav
Tahir
Viru

63
Example of Sorting the elements of List that contains Wrapper class objects

1. import java.util.*;
2. class TestSort2{
3. public static void main(String args[]){
4.
5. ArrayList al=new ArrayList();
6. al.add(Integer.valueOf(201));
7. al.add(Integer.valueOf(101));
8. al.add(230);//internally will be converted into objects as Integer.valueOf(230)
9.
10. Collections.sort(al);
11.
12. Iterator itr=al.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. }
17. }
O/P :

101
201
230

64
Java Comparable interface
Java Comparable interface is used to order the objects of user-defined class.This interface is
found in java.lang package and contains only one method named compareTo(Object). It
provide single sorting sequence only i.e. you can sort the elements on based on single data
member only. For example it may be rollno, name, age or anything else.

compareTo(Object obj) method

public int compareTo(Object obj): is used to compare the current object with the specified
object.

We can sort the elements of:

 String objects
 Wrapper class objects
 User-defined class objects

Collections class

Collections class provides static methods for sorting the elements of collections. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But We cannot sort the elements
of List. Collections class provides methods for sorting the elements of List type elements.

Method of Collections class for sorting List elements

public void sort(List list): is used to sort the elements of List. List elements must be of
Comparable type.

Note: String class and Wrapper classes implements Comparable interface by default. So
if you store the objects of string or wrapper classes in list, set or map, it will be
Comparable by default.

65
Java Comparable Example

The example of Comparable interface that sorts the list elements on the basis of age.

File: Student.java

1. class Student implements Comparable<Student>{


2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10.
11. public int compareTo(Student st){
12. if(age==st.age)
13. return 0;
14. else if(age>st.age)
15. return 1;
16. else
17. return -1;
18. }
19. }

File: TestSort3.java

1. import java.util.*;
2. import java.io.*;
3. public class TestSort3{
4. public static void main(String args[]){
5. ArrayList<Student> al=new ArrayList<Student>();
6. al.add(new Student(101,"Vijay",23));
7. al.add(new Student(106,"Ajay",27));
8. al.add(new Student(105,"Jai",21));
9.
10. Collections.sort(al);
11. for(Student st:al){
12. System.out.println(st.rollno+" "+st.name+" "+st.age);
13. }
14. }
15. }

O/P:

105 Jai 21
101 Vijay 23
106 Ajay 27

66
Java Comparator interface
Java Comparator interface is used to order the objects of user-defined class.

This interface is found in java.util package and contains 2 methods compare(Object


obj1,Object obj2) and equals(Object element).

It provides multiple sorting sequence i.e. you can sort the elements on the basis of any data
member, for example rollno, name, age or anything else.

compare() method

public int compare(Object obj1,Object obj2): compares the first object with second object.

 Collections class

Collections class provides static methods for sorting the elements of collection. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. But we cannot sort the elements
of List. Collections class provides methods for sorting the elements of List type elements also.

Method of Collections class for sorting List elements

public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

Java Comparator Example (Non-generic Old Style)

Let's see the example of sorting the elements of List on the basis of age and name. In this
example, we have created 4 java classes:

 Student.java
 AgeComparator.java
 NameComparator.java
 Simple.java

67
Student.java

This class contains three fields rollno, name and age and a parameterized constructor.

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

AgeComparator.java

This class defines comparison logic based on the age. If age of first object is greater than the
second, we are returning positive value, it can be any one such as 1, 2 , 10 etc. If age of first
object is less than the second object, we are returning negative value, it can be any negative
value and if age of both objects are equal, we are returning 0.

1. import java.util.*;
2. class AgeComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. if(s1.age==s2.age)
8. return 0;
9. else if(s1.age>s2.age)
10. return 1;
11. else
12. return -1;
13. }
14. }

NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

1. import java.util.*;
2. class NameComparator implements Comparator{
3. public int compare(Object o1,Object o2){
4. Student s1=(Student)o1;
5. Student s2=(Student)o2;
6.
7. return s1.name.compareTo(s2.name);
8. }
9. }

68
Simple.java

In this class, we are printing the objects values by sorting on the basis of name and age.

1. import java.util.*;
2. import java.io.*;
3.
4. class Simple{
5. public static void main(String args[]){
6.
7. ArrayList al=new ArrayList();
8. al.add(new Student(101,"Vijay",23));
9. al.add(new Student(106,"Ajay",27));
10. al.add(new Student(105,"Jai",21));
11.
12. System.out.println("Sorting by Name...");
13.
14. Collections.sort(al,new NameComparator());
15. Iterator itr=al.iterator();
16. while(itr.hasNext()){
17. Student st=(Student)itr.next();
18. System.out.println(st.rollno+" "+st.name+" "+st.age);
19. }
20.
21. System.out.println("sorting by age...");
22.
23. Collections.sort(al,new AgeComparator());
24. Iterator itr2=al.iterator();
25. while(itr2.hasNext()){
26. Student st=(Student)itr2.next();
27. System.out.println(st.rollno+" "+st.name+" "+st.age);
28. }
29.
30.
31. }
32. }
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27

69
Java Comparator Example (Generic)

Student.java

1. class Student{
2. int rollno;
3. String name;
4. int age;
5. Student(int rollno,String name,int age){
6. this.rollno=rollno;
7. this.name=name;
8. this.age=age;
9. }
10. }

AgeComparator.java

1. import java.util.*;
2. class AgeComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. if(s1.age==s2.age)
5. return 0;
6. else if(s1.age>s2.age)
7. return 1;
8. else
9. return -1;
10. }
11. }

NameComparator.java

This class provides comparison logic based on the name. In such case, we are using the
compareTo() method of String class, which internally provides the comparison logic.

1. import java.util.*;
2. class NameComparator implements Comparator<Student>{
3. public int compare(Student s1,Student s2){
4. return s1.name.compareTo(s2.name);
5. }
6. }

70
Simple.java

In this class, we are printing the objects values by sorting on the basis of name and age.

1. import java.util.*;
2. import java.io.*;
3. class Simple{
4. public static void main(String args[]){
5.
6. ArrayList<Student> al=new ArrayList<Student>();
7. al.add(new Student(101,"Vijay",23));
8. al.add(new Student(106,"Ajay",27));
9. al.add(new Student(105,"Jai",21));
10.
11. System.out.println("Sorting by Name...");
12.
13. Collections.sort(al,new NameComparator());
14. for(Student st: al){
15. System.out.println(st.rollno+" "+st.name+" "+st.age);
16. }
17.
18. System.out.println("sorting by age...");
19.
20. Collections.sort(al,new AgeComparator());
21. for(Student st: al){
22. System.out.println(st.rollno+" "+st.name+" "+st.age);
23. }
24.
25. }
26. }

O/P:

Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27

71
Properties class in Java
The properties object contains key and value pair both as a string. The java.util.Properties
class is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class provides
methods to get data from properties file and store data into properties file. Moreover, it can be
used to get properties of system.

Advantage of properties file

Recompilation is not required, if information is changed from properties file: If any


information is changed from the properties file, you don't need to recompile the java class. It
is used to store information which is to be changed frequently.

Methods of Properties class

The commonly used methods of Properties class are given below.

Method Description
public void load(Reader r) loads data from the Reader object.
public void load(InputStream is) loads data from the InputStream object
public String getProperty(String key) returns value based on the key.
public void setProperty(String key,String value) sets the property in the properties
object.
public void store(Writer w, String comment) writers the properties in the writer
object.
public void store(OutputStream os, String comment) writes the properties in the
OutputStream object.
storeToXML(OutputStream os, String comment) writers the properties in the writer
object for generating xml document.
public void storeToXML(Writer w, String comment, writers the properties in the writer
String encoding) object for generating xml document
with specified encoding.

72
Example of Properties class to get information from properties file

To get information from the properties file, create the properties file first.

db.properties

user=system
password=oracle

Now, create the java class to read the data from the properties file.

Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5. FileReader reader=new FileReader("db.properties");
6.
7. Properties p=new Properties();
8. p.load(reader);
9.
10. System.out.println(p.getProperty("user"));
11. System.out.println(p.getProperty("password"));
12. }
13. }
O/P:

system
oracle

Now if you change the value of the properties file, you don't need to compile the java
class again. That means no maintenance problem.

73
Example of Properties class to get all the system properties

By System.getProperties() method we can get all the properties of system. Let's create the
class that gets information from the system properties.

Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=System.getProperties();
7. Set set=p.entrySet();
8.
9. Iterator itr=set.iterator();
10. while(itr.hasNext()){
11. Map.Entry entry=(Map.Entry)itr.next();
12. System.out.println(entry.getKey()+" = "+entry.getValue());
13. }
14.
15. }
16. }
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
...........

74
Example of Properties class to create properties file

Now write the code to create the properties file.

Test.java

1. import java.util.*;
2. import java.io.*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. p.setProperty("name","Sonoo Jaiswal");
8. p.setProperty("email","sonoojaiswal@javatpoint.com");
9.
10. p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");
11.
12. }
13. }

Let's see the generated properties file.

info.properties

1. #Javatpoint Properties Example


2. #Thu Oct 03 22:35:53 IST 2013
3. email=sonoojaiswal@javatpoint.com
4. name=Sonoo Jaiswal

75
Difference between ArrayList and Vector
ArrayList and Vector both implements List interface and maintains insertion order.

But there are many differences between ArrayList and Vector classes that are given below.

ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of current Vector increments 100% means doubles the array size
array size if number of element exceeds if total number of element exceeds than its capacity.
from its capacity.
3) ArrayList is not a legacy class, it is Vector is a legacy class.
introduced in JDK 1.2.
4) ArrayList is fast because it is non- Vector is slow because it is synchronized i.e. in
synchronized. multithreading environment, it will hold the other
threads in runnable or non-runnable state until current
thread releases the lock of object.
5) ArrayList uses Iterator interface to Vector uses Enumeration interface to traverse the
traverse the elements. elements. But it can use Iterator also.

Example of Java ArrayList

Let's see a simple example where we are using ArrayList to store and traverse the elements.

1. import java.util.*;
2. class TestArrayList21{
3. public static void main(String args[]){
4.
5. List<String> al=new ArrayList<String>();//creating arraylist
6. al.add("Sonoo");//adding object in arraylist
7. al.add("Michael");
8. al.add("James");
9. al.add("Andy");
10. //traversing elements using Iterator
11. Iterator itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

O/P :

Sonoo
Michael
James
Andy

76
Example of Java Vector

Simple example of java Vector class that uses Enumeration interface.

1. import java.util.*;
2. class TestVector1{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();//creating vector
5. v.add("umesh");//method of Collection
6. v.addElement("irfan");//method of Vector
7. v.addElement("kumar");
8. //traversing elements using Enumeration
9. Enumeration e=v.elements();
10. while(e.hasMoreElements()){
11. System.out.println(e.nextElement());
12. }
13. }
14. }

O/P :

umesh
irfan
kumar

77

You might also like