Unit-4 Study Material Java
Unit-4 Study Material Java
Java Collections can achieve all the operations that you perform on a data such
as searching, sorting, insertion, manipulation, and deletion.
Let us see the hierarchy of Collection framework. The java.util package contains
all the classes and interfaces for the Collection framework.
4) Iterator Interface ---
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
No. Method Description
1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.
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 less
used.
5) Collection Interface ---- The Collection interface is the interface which is
implemented by all the classes in the collection framework. It declares the
methods that every collection will have. In other words, we can say that the
Collection interface builds the foundation on which the collection framework
depends.
Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by all
the subclasses of Collection interface.
6) List Interface --- List interface is the child interface of Collection interface. It
inhibits a list type data structure in which we can store the ordered collection of
objects. It can have duplicate values.
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
7) ArrayList ---- The ArrayList class implements the List interface. It uses a
dynamic array to store the duplicate element of different data types. The
ArrayList class maintains the insertion order and is non-synchronized. The
elements stored in the ArrayList class can be randomly accessed. Consider the
following example.
1. import java.util.*;
2. class TestJavaCollection1{
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. }
Output:
Ravi
Vijay
Ravi
Ajay
1. import java.util.*;
2. public class TestJavaCollection2{
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. }
Output:
Ravi
Vijay
Ravi
Ajay
9) Vector ---- Vector uses a dynamic array to store the data elements. It is similar
to ArrayList. However, It is synchronized and contains many methods that are
not the part of Collection framework.
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. .add("Amit");
6. v.add("Ashish");
7. v.add("Garima");
8. Iterator<String> itr=v.iterator();
9. while(itr.hasNext()){
10. System.out.println(itr.next());
11. }
12. }
13. }
Output:
Ayush
Amit
Ashish
Garima
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
11) Queue Interface --- Queue Interface
There are various classes that implement the Queue interface, some of them are
given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow
null values to be stored in the queue.
1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue elements:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two elements:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
ArrayDeque
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }
Output:
Gautam
Karan
Ajay
12) Set Interface--- Set Interface in Java is present in java.util package. It extends
the Collection interface. It represents the unordered set of elements which doesn't
allow us to store the duplicate items. We can store at most one null value in Set.
Set is implemented by HashSet, LinkedHashSet, and TreeSet.
13) HashSet --- HashSet class implements Set Interface. It represents the
collection that uses a hash table for storage. Hashing is used to store the elements
in the HashSet. It contains unique items.
1. import java.util.*;
2. public class TestJavaCollection7{
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. }
Output:
Vijay
Ravi
Ajay
1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ajay
15) SortedSet Interface --- ortedSet is the alternate of Set interface that provides
a total ordering on its elements. The elements of the SortedSet are arranged in the
increasing (ascending) order. The SortedSet provides the additional methods that
inhibit the natural ordering of the elements.
16) TreeSet--- Java TreeSet class implements the Set interface that uses a tree for
storage. Like HashSet, TreeSet also contains unique elements. However, the
access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored
in ascending order.
1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<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. }
Output:
Ajay
Ravi
Vijay
17) 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. A Map contains unique
keys.A Map is useful if you have to search, update or delete elements on the basis
of a key.
1. import java.util.*;
2. public class MapExample1 {
3. public static void main(String[] args) {
4. Map map=new HashMap();
5. //Adding elements to map
6. map.put(1,"Amit");
7. map.put(5,"Rahul");
8. map.put(2,"Jai");
9. map.put(6,"Amit");
10. //Traversing Map
11. Set set=map.entrySet();//Converting to Set so that we can traverse
12. Iterator itr=set.iterator();
13. while(itr.hasNext()){
14. //Converting to Map.Entry so that we can get key and value separatel
y
15. Map.Entry entry=(Map.Entry)itr.next();
16. System.out.println(entry.getKey()+" "+entry.getValue());
17. }
18. }
19. }
Output
1.Amit
2. Jai
3. Rahul
4. Amit
18) HashMap Class---- Java HashMap class implements the Map interface
which allows us to store key and value pair, where keys should be unique. If you
try to insert the duplicate key, it will replace the element of the corresponding
key. It is easy to perform operations using the key index like updation, deletion,
etc. HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It
allows us to store the null elements as well, but there should be only one null key.
Since Java 5, it is denoted as HashMap<K,V> where K stands for key and V for
value. It inherits the AbstractMap class and implements the Map interface.
Output:100 Amit
101 Vijay
102 Rahul
20) TreeMap Class ---- Java TreeMap class is a red-black tree based
implementation. It provides an efficient means of storing key-value pairs in
sorted order.
o Java TreeMap contains values based on the key. It implements the
NavigableMap interface and extends AbstractMap class.
o Java TreeMap contains only unique elements.
o Java TreeMap cannot have a null key but can have multiple null values.
o Java TreeMap is non synchronized.
o Java TreeMap maintains ascending order.
1. import java.util.*;
2. class TreeMap1{
3. public static void main(String args[]){
4. TreeMap<Integer,String> map=new TreeMap<Integer,String>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9.
10. for(Map.Entry m:map.entrySet()){
11. System.out.println(m.getKey()+" "+m.getValue());
12. }
13. }
14. }
Output:100 Amit
101 Vijay
102 Ravi
103 Rahul
HashMap TreeMap
1) HashMap can contain one null key. TreeMap cannot contain any null key.
21) Hashtable Class ---- Java Hashtable class implements a hashtable, which
maps keys to values. It inherits Dictionary class and implements the Map
interface.
o A Hashtable is an array of a list. Each list is known as a bucket. The position
of the bucket is identified by calling the hashcode() method. A Hashtable
contains values based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is
0.75.
Output:
103 Rahul
102 Ravi
101 Vijay
100 Amit
22) Sorting--- We can sort the elements of:
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class provides static methods for sorting the elements of a collection. If
collection elements are of a Set type, we can use TreeSet. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List
type elements.
Output
Mukesh
Saurav
Tahir
Viru
Example to sort string objects in reverse order
1. import java.util.*;
2. class TestSort2{
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,Collections.reverseOrder());
12. Iterator i=al.iterator();
13. while(i.hasNext())
14. {
15. System.out.println(i.next());
16. }
17. }
18. }
Viru
Tahir
Saurav
Mukesh
Java Comparable interface is used to order the objects of the user-defined class.
This interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort
the elements on the basis of single data member only. For example, it may be
rollno, name, age or anything else.
Let's see the example of the Comparable interface that sorts the list elements on
the basis of age.
File: Student.java
File: TestSort1.java
1. import java.util.*;
2. public class TestSort1{
3. public static void main(String args[]){
4. ArrayList<Student> al=new ArrayList<Student>();
5. al.add(new Student(101,"Vijay",23));
6. al.add(new Student(106,"Ajay",27));
7. al.add(new Student(105,"Jai",21));
8.
9. Collections.sort(al);
10. for(Student st:al){
11. System.out.println(st.rollno+" "+st.name+" "+st.age);
12. }
13. }
14. }
105 Jai 21
101 Vijay 23
106 Ajay 27
It provides multiple sorting sequences, i.e., you can sort the elements on the basis
of any data member, for example, rollno, name, age or anything else.
Method Description
public int compare(Object obj1, It compares the first object with the second
Object obj2) object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
public boolean equals(Object obj) It is used to compare the current object with the
specified object.
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:
1. Student.java
2. AgeComparator.java
3. NameComparator.java
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 the age of the first object
is greater than the second, we are returning a positive value. It can be anyone such
as 1, 2, 10. If the age of the first object is less than the second object, we are
returning a negative value, it can be any negative value, and if the age of both
objects is 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. }
25) 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 the properties file and store data into the
properties file. Moreover, it can be used to get the properties of a system.
An Advantage of the properties file
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. }
Output:system
oracle
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. }