Java Unit-Iv
Java Unit-Iv
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).
o It is optional.
2. Algorithm
1
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
2 public boolean addAll(Collection is used to insert the specified collection elements in the
c) invoking collection.
2
element)
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.
Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.
3
No. Method Description
2 public Object next() It returns the element and moves the cursor pointer to the next
element.
3 public void remove() It removes the last elements returned by the iterator. It is rarely
used.
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and
implements List interface.
o Java ArrayList allows random access because array works at the index basis.
4
o 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.
ArrayList(Collection It is used to build an array list that is initialized with the elements of the
c) collection c.
ArrayList(int It is used to build an array list that has the specified initial capacity.
capacity)
void add(int index, Object It is used to insert the specified element at the specified position index
element) in a list.
boolean addAll(Collection It is used to append all of the elements in the specified collection to the
c) 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.
5
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[] It is used to return an array containing all of the elements in this list in
a) 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, It is used to insert all of the elements in the specified collection into this
Collection c) list, starting at the specified position.
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 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.
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.
For more information of java generics, click here Java Generics Tutorial.
6
Java ArrayList Example
import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ravi
Ajay
1. By Iterator interface.
2. 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.
7
Ravi
Vijay
Ravi
Ajay
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
import java.util.*;
public class TestCollection3{
public static void main(String args[]){
//Creating user-defined class objects
Student s1=new Student(101,"Sonoo",23);
Student s2=new Student(102,"Ravi",21);
Student s2=new Student(103,"Hanumat",25);
//creating arraylist
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);//adding Student class object
al.add(s2);
al.add(s3);
//Getting Iterator
Iterator itr=al.iterator();
//traversing elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
101 Sonoo 23
102 Ravi 21
103 Hanumat 25
8
Example of addAll(Collection c) method
import java.util.*;
class TestCollection4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
al.addAll(al2);//adding second list in first list
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ravi
Vijay
Ajay
Sonoo
Hanumat
}
9
}
iterating the elements after removing the elements of al2...
Vijay
Ajay
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
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;
}
10
}
public class ArrayListExample {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<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 list
list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list
for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
11
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.
12
LinkedList class declaration
Let's see the declaration for java.util.LinkedList class.
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.
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.
13
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.
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:Ravi
Vijay
Ravi
Ajay
Output:
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
from the array, all the bits are shifted in memory. no bit shifting is required in memory.
15
3) ArrayList class can act as a list only because LinkedList class can act as a list and
it implements List only. queue both because it implements List and
Deque interfaces.
4) ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.
void add(int index,Object It is used to insert element into the invoking list at the index
element) passed in the index.
boolean addAll(int It is used to insert all elements of c into the invoking list at the
index,Collection c) 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 It is used to assign element to the location specified by index
element) 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.
16
Java List Example
import java.util.*;
public class ListExample{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Amit");
al.add("Vijay");
al.add("Kumar");
al.add(1,"Sachin");
System.out.println("Element at 2nd position: "+al.get(2));
for(String s:al){
System.out.println(s);
}
}
}
Output:
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 This method return true if this list iterator has more elements when
hasPrevious() traversing the list in the reverse direction.
17
Object previous() This method return the previous element in the list and moves the cursor
position backwards.
Output:
Output:
19
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.
20
HashSet() It is used to construct a default HashSet.
HashSet(Collection It is used to initialize the hash set by using the elements of the collection c.
c)
HashSet(int It is used to initialize the capacity of the hash set to the given integer value
capacity) capacity. The capacity grows automatically as elements are added to the
HashSet.
void clear() It is used to remove all of the elements from this set.
boolean It is used to return true if this set contains the specified element.
contains(Object o)
boolean add(Object o) It is used to adds the specified element to this set if it is not already
present.
boolean remove(Object It is used to remove the specified element from this set if it is present.
o)
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.
21
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Ajay
Vijay
Ravi
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
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> set=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
22
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
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.
23
o Access and retrieval times are quiet fast.
TreeSet() It is used to construct an empty tree set that will be sorted in an ascending orde
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 It is used to construct an empty tree set that will be sorted according to given co
comp)
TreeSet(SortedSet ss) It is used to build a TreeSet that contains the elements of the given SortedSet.
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.
24
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 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.
Output:
Ajay
Ravi
Vijay
25
Java TreeSet Example: Book
Let's see a 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.
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
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 int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
}
public class TreeSetExample {
public static void main(String[] args) {
Set<Book> set=new TreeSet<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
//Adding Books to TreeSet
set.add(b1);
set.add(b2);
set.add(b3);
//Traversing TreeSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
26
}
}
}
Output:
boolean It is used to insert the specified element into this queue and return true upon
add(object) success.
Object poll() It is used to retrieves and removes the head of this queue, or returns null if this
queue is empty.
Object It is used to retrieves, but does not remove, the head of this queue.
element()
Object peek() It is used to retrieves, but does not remove, the head of this queue, or returns
null if this queue is empty.
27
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.
import java.util.*;
class Book implements Comparable<Book>{
int id;
String name,author,publisher;
int quantity;
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 int compareTo(Book b) {
if(id>b.id){
return 1;
}else if(id<b.id){
return -1;
}else{
return 0;
}
}
}
public class LinkedListExample {
public static void main(String[] args) {
Queue<Book> queue=new PriorityQueue<Book>();
//Creating Books
Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
//Adding Books to the queue
queue.add(b1);
queue.add(b2);
queue.add(b3);
System.out.println("Traversing the queue elements:");
29
//Traversing queue elements
for(Book b:queue){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
queue.remove();
System.out.println("After removing one book record:");
for(Book b:queue){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}
Output:
boolean It is used to insert the specified element into this deque and return true upon
add(object) success.
30
Object poll() It is used to retrieves and removes the head of this deque, or returns null if this
deque is empty.
Object It is used to retrieves, but does not remove, the head of this deque.
element()
Object peek() It is used to retrieves, but does not remove, the head of this deque, or returns
null if this deque is empty.
ArrayDeque class
The ArrayDeque class provides the facility of using deque and resizable-array. It inherits
AbstractCollection class and implements the Deque interface.
31
o ArrayDeque has no capacity restrictions.
ArrayDeque Hierarchy
The hierarchy of ArrayDeque class is given in the figure displayed at the right side of the page.
Output:
Ravi
Vijay
Ajay
32
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque){
System.out.println(s);
}
//deque.poll();
//deque.pollFirst();//it is same as poll()
deque.pollLast();
System.out.println("After pollLast() Traversal...");
for(String s:deque){
System.out.println(s);
}
}
}
Output:
Map is useful if you have to search, update or delete elements on the basis of key.
33
A Map doesn't allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap
allow null keys and values, but TreeMap doesn't allow any null key or value.
A Map can't be traversed, so you need to convert it into Set using keySet() or entrySet() method.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any order.
34
value)
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.
Output:
102 Rahul
100 Amit
101 Vijay
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
36
Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap class and
implements Map interface.
o It maintains no order.
37
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 map
fillRatio) by using its arguments.
void clear() It is used to remove all of the mappings from this map.
boolean It is used to return true if this map contains a mapping for the specified
containsKey(Object key) key.
boolean It is used to return true if this map maps one or more keys to the
containsValue(Object specified value.
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, It is used to associate the specified value with the specified key in this
Object value) map.
int size() It is used to return the number of key-value mappings in this map.
38
Collection values() It is used to return a collection view of the values contained in this
map.
Output:
39
Difference between HashSet and HashMap
HashSet contains only values whereas HashMap contains entry(key and value).
//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);
}
}
}
Output:
40
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
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.
41
Constructors of Java LinkedHashMap class
Constructor Description
LinkedHashMap(int capacity, float It is used to initialize both the capacity and the fillRatio.
fillRatio)
Object get(Object key) It is used to return the value to which this map maps the specified
key.
boolean containsKey(Object It is used to return true if this map maps one or more keys to the
key) specified value.
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
42
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:100 Amit
101 Vijay
102 Rahul
Output:
43
Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing
key/value pairs in sorted order.
o A TreeMap contains values based on the key. It implements the NavigableMap interface and
extends AbstractMap class.
o It cannot have null key but can have multiple null values.
TreeMap() It is used to construct an empty tree map that will be sorted using the
natural order of its key.
TreeMap(Comparator It is used to construct an empty tree-based map that will be sorted using
comp) 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.
44
Methods of Java TreeMap class
Method Description
boolean containsKey(Object It is used to return true if this map contains a mapping for the
key) specified key.
boolean It is used to return true if this map maps one or more keys to the
containsValue(Object value) 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
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
Output:
1) HashMap can contain one null key. TreeMap can not contain any null key.
46
2) HashMap maintains no order. TreeMap maintains ascending order.
o 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.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
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, It is used to create a hash table that has an initial size specified by size and
float fillRatio) a fill ratio specified by fillRatio.
47
Methods of Java Hashtable class
Method Description
boolean contains(Object This method return true if some value equal to the value exist within
value) the hash table, else return false.
boolean This method return true if some value equal to the value exists within
containsValue(Object the hash table, else return false.
value)
boolean This method return true if some key equal to the key exists within the
containsKey(Object key) 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.
hm.put(100,"Amit");
hm.put(102,"Ravi");
48
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
Output:
But there are many differences between HashMap and Hashtable classes that are given below.
49
HashMap Hashtable
2) HashMap allows one null key and multiple null Hashtable doesn't allow any null
values. key or value.
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.
1. Student.java
2. AgeComparator.java
3. NameComparator.java
4. Simple.java
Student.java
This class contains three fields rollno, name and age and a parameterized constructor.
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
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.
import java.util.*;
class AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
51
}
}
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.
import java.util.*;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
52
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
105 Jai 21
101 Vijay 23
106 Ajay 27
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
AgeComparator.java
import java.util.*;
class AgeComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
if(s1.age==s2.age)
return 0;
else if(s1.age>s2.age)
return 1;
else
return -1;
}
}
NameComparator.java
53
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.
import java.util.*;
class NameComparator implements Comparator<Student>{
public int compare(Student s1,Student s2){
return s1.name.compareTo(s2.name);
}
}
Simple.java
In this class, we are printing the objects values by sorting on the basis of name and age.
import java.util.*;
import java.io.*;
class Simple{
public static void main(String args[]){
System.out.println("Sorting by Name...");
Collections.sort(al,new NameComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Output:Sorting by Name...
106 Ajay 27
105 Jai 21
101 Vijay 23
Sorting by age...
54
105 Jai 21
101 Vijay 23
106 Ajay 27
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.
Method Description
public void load(InputStream is) loads data from the InputStream object
public void setProperty(String key,String sets the property in the properties object.
value)
public void store(Writer w, String writers the properties in the writer object.
comment)
public void store(OutputStream os, String writes the properties in the OutputStream object.
comment)
storeToXML(OutputStream os, String writers the properties in the writer object for
comment) generating xml document.
55
public void storeToXML(Writer w, String writers the properties in the writer object for
comment, String encoding) generating xml document with specified encoding.
db.properties
1. user=system
2. password=oracle
Now, lets create the java class to read the data from the properties file.
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output: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.
Test.java
import java.util.*;
import java.io.*;
public class Test {
56
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
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
...........
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","[email protected]");
9.
10. p.store(new FileWriter("info.properties"),"Javatpoint Properties Example");
11.
12. }
13. }
57
Let's see the generated properties file.
info.properties
58
59
60
61
62
63
64
65
66
67
68
69