Java, .NET, PHP, PYTHON, ANGULAR, .NET, ML, Data Scince, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Collection Framework in JAVA:-

The collection is the enhancement of array. It provides a set of interfaces and classes to store data dynamically.

Collection Framework  Tutorials in JAVA, ArrayList, Vector, Set, Map, etc:-

The collection framework is used to store a collection of similar and dissimilar datatype both, we can store elements dynamically without providing size. it will be automatically managed according to inserted elements.

Collection Objects store data using dynamic memory allocation and contain common datatype values .means it solves the limitation of the array for datatype and fixed in size problem.


Java provides a collection framework using Set of Interfaces, Classes, and Methods to provide Collection Object according to different functionality.

..........................................................................................................................................................






Iterable Interface:-

It is the base interface of all Collection Interfaces of Java.

Collection Interface:-

It is the child Interface of Iterable which contains a set of rules which will be implemented by Other SubInterfaces.

Methods  of collection interface 

add()  :-  It is used to add element in Collection Object

remove():-  It is used to remove an element from Collection Object

addAll() :-  It is used to add multiple elements in Collection Object

removeAll():-  It is used to remove all elements from Collection Object

size():-  It is used to return the size of Collection Objects.

clear() :-  remove all elements of particular collection reference.

contains():-  this method is used to check a particular element is exists or not?

equals():-  it is used to compare Object references corresponding value.

hashcode():-  It is used to return the address of the current object.




List Interface:-  It is the interface which contains all rules of Collection Interfaces, List Features will be implemented by ArrayList, LinkedList, and Vector class.
All elements of the List Interface will be store data in proper sequences.

public List extends Collection







Classes of List Interface:-

1.1 ArrayList:-

This class provides a dynamic object which contains a collection of similar and dissimilar datatype both.

ArrayList has combine features of Array and List both means we can access the ArrayList element using Index and address both.

Syntax of ArrayList:-


ArrayList ref = new ArrayList();
ref.add(element1);
ref.add(element2);
ref.add(element3);
ref.remove(element1);

import java.util.ArrayList;

public class ArrayListExample {

public static void main(String args[])
{
ArrayList obj = new ArrayList();
obj.add("Java");
obj.add(".NET");
obj.add("PHP");
obj.add("C");
obj.add("CPP");
obj.add(12);
obj.add(23);
obj.add(23.45);
obj.remove("Java");
for(int i=0;i<obj.size();i++)
{
System.out.println(obj.get(i));
}
for(Object o:obj)
{
System.out.println(o);
}
}
}


Generic ArrayList:-

using this we can store an element of ArrayList according to generic classes using wrapper classes.

A wrapper class is used to convert the primitive data type of Java to Object pattern, for example, int is a primitive datatype, if we want to convert int to Object type then we can use the Integer Wrapper class.






Wrapper class provides type safety under Collection object.

Wrapper class provides immutable objects means we can not change the Wrapper class dynamically.

Integer    for int

Float      for float

Double  for double

String  for char array

Byte    for byte

Short   for short

Long for long

Character   for char


ArrayList<Integer> obj = new ArrayList<Integer>();
obj.add(10);
obj.add(20);
obj.add(30);


Generic ArrayList using Class


Create Emp class:-

package oops;

public class Emp {
private int empid;
private String empname;
Emp(int empid,String empname)
{
this.empid = empid;
this.empname=empname;
}

public String toString()
{
return "empid is "+empid+ " empname is "+empname;
}
}


Create a Main class to call features:-

package oops;

import java.util.ArrayList;

public class ArrayListEmp {

public static void main(String[] args) {
ArrayList<Emp> obj = new ArrayList<Emp>();
obj.add(new Emp(1001,"xyz"));
obj.add(new Emp(1002,"mno"));
obj.add(new Emp(1000,"klmn"));
for(Emp e:obj)
{
System.out.println(e);
}

}

}


First Create Student class:-

public class Student {
private int rno;
private String sname;

Student(int rno,String sname)
{
this.rno=rno;
this.sname=sname;

}
public int getRno() {
return rno;
}
public void setRno(int rno) {
this.rno = rno;
}
public String getSname() {
return same;
}
public void setSname(String sname) {
this.sname = sname;
}



}


ArrayList<Student> obj = new ArrayList<Student>();
obj.add(new Student(1001,"manish"))
obj.add(new Student(1002,"Jay"))


Complete Code Explanation of ArrayList Class:-


package collection example;
import java.util.*;

public class Example1 {
    
    public void arrList()
    {
      /*  ArrayList obj = new ArrayList();
        obj.add("JAVA");
        obj.add(15000);
        obj.add(".NET");
        obj.add(12000);
        obj.add("PHP");
        obj.add(true);
        obj.add("iOS");
        obj.add(14000.2F);
        obj.remove("JAVA");*/
    /*    ArrayList<Integer> obj = new ArrayList<Integer>();
        obj.add(10);
        obj.add(20);
        obj.add(30);*/
        ArrayList<Student> obj = new ArrayList<Student>();
        obj.add(new Student(1001,"manish"));
        obj.add(new Student(1002,"Jay"));


        for(Student o:obj)
        {
            System.out.println(o.getRno()+" "+o.getSname());
        }
       /* for (int i = 0; i < obj.size(); i++) {
            System.out.println(obj.get(i));
            
        }*/
    }
    public static void main(String[] args) {
        Example1 obj= new Example1();
        obj.arrList();
    }
            
    

}


ASSIGNMENT OF ArrayList:-


1 WAP to find max element in ArrayList

2 WAP to sort the elements of ArrayList using Student class(rno,name,branch ,fees) sort by iron, fees?



package collectionexample;
import java.util.*;

public class ArrayListExample {
    
    public static void main(String[] args) {
        ArrayList<Integer> obj = new ArrayList<Integer>();
      /*  obj.add("C");
        obj.add("CPP");
        obj.add("DS");
        obj.add(1001);
        obj.add("PHP");*/
        obj.add(12);
        obj.add(2);
        obj.add(31);
        obj.add(4);
        for (int i = 0; i < obj.size(); i++) {
            for(int j=i+1;j<obj.size();j++)
            {
                if(obj.get(i)<obj.get(j))
                {
                    int temp = obj.get(i);
                    obj.set(i, obj.get(j));
                    obj.set(j, temp);
                }
            }
            System.out.println(obj.get(i));
        }

       
        
        
      /*  for(Object o:obj)
        {
            System.out.println(o);
        }*/
    }
    
}


................................................................................................................................

LinkedList:-
....................................................................................................................

It is the class that implements the features of List Interface. We can add, edit, and delete elements dynamically on LinkedList.

LinkedList class will follow the features of  LIST, QUEUE, and DEQUEUE Interface.

We can add element from any position(begin, ending, specific position)

Syntax of LinkedList

LinkedList ref = new LinkedList();
ref.add("object")
ref.addFirst("data1")
ref.addLast("data2")
ref.remove("object")

...................................................................................

LinkedList Example in Java with Program:-


import java.util.LinkedList;

public class Example2 {
    
    public static void main(String[] args) {
       /* LinkedList obj = new LinkedList();
        obj.add("C");
        obj.add("CPP");
        obj.add(123);
        obj.add(12.34F);
        obj.add(12.34);
        obj.addFirst("DS");
        obj.addLast("JAVA");
        obj.add(1, "PYTHON");
        obj.remove("C");*/
        LinkedList<Integer> obj = new LinkedList<Integer>();
        obj.add(1001);
        obj.add(1005);
        obj.add(1007);
        obj.add(1009);
        for(Object o:obj)
        {
            System.out.println("result is "+o);
        }
        
    }
    

}


...................................................................................................................................................



Vector:-   

Vector class will be used to define the set of rules of List interface means Vector class will be implemented By List.

It is similar to ArrayList but the ArrayList class can not be synchronized but the Vector class can be synchronized.

Syntax of Vector:-


Vector ref = new Vector();
ref.add(element);
ref.add(element);
ref.add(element);
ref.remove(element);

import java.util.Vector;

public class VectorExample {
    public static void main(String[] args) {
        Vector obj = new Vector();
        obj.add("C");
        obj.add("CPP");
        obj.add("JAVA");
        obj.remove("C");
        obj.add("PHP");
        obj.add(1001);
        for(Object o:obj)
        {
            System.out.println(o);
        }
        
        
    }
    
}


Stack:-

It is the child class of vector and provides the LIFO concept.  

package oops;

import java.util.Stack;

public class StackExample {

public static void main(String[] args) {
Stack<Integer> obj = new Stack<Integer>();
obj.push(1001);
obj.push(1004);
obj.push(1000);
System.out.print(obj.pop());

}

}

.................................................................................................................................................

Set Interface:-

This interface contains elements without any sequence, we can store an element randomly.

duplicate elements are not allowed in Set.


Classes of Set Interface:-

1 HashSet:-

It is the predefined class which stores element without any order and display elements randomly.

HashSet ref = new HashSet();
ref.add(value1);
ref.add(value2);
ref.remove();


package collectionexample;

import java.util.HashSet;


public class HashSetExample {
    
    public static void main(String[] args) {
        HashSet obj = new HashSet();
        obj.add("C");
        obj.add("CPP");
        obj.add("DS");
        obj.add("DS");
        obj.add("JAVA");
        obj.add(1001);
        obj.add(1002);
        obj.add(".NET");
        for(Object o:obj)
        {
            System.out.println(o);
        }
        
        
    }
    

}




2 LinkedHashSet:-  

All elements of the set will be connected with each other hence it displays data according to the insertion order.

LinkedHashset ref = new LinkedHashset();

public class HashSetExample {
    
    public static void main(String[] args) {
        LinkedHashSet obj = new LinkedHashSet();
        obj.add("C");
        obj.add("CPP");
        obj.add("DS");
        obj.add("DS");
        obj.add("JAVA");
        obj.add(1001);
        obj.add(1002);
        obj.add(".NET");
        for(Object o:obj)
        {
            System.out.println(o);
        }
        
        
    }
    

}


3 TreeSet:-


All elements of Set will be displayed using a tree structure.it displays records using asc order.


TreeSet ref = new TreeSet();
ref.add("item");
ref.add("item2");

 public class HashSetExample {
  
    public static void main(String[] args) {
       // HashSet obj = new HashSet();
       // LinkedHashSet obj = new LinkedHashSet();
       TreeSet obj = new TreeSet();
        obj.add(12);
        obj.add(9);
        obj.add(23);
        obj.add(17);
        obj.add(15);
      
        for(Object o:obj)
        {
            System.out.println(o);
        }
      
      
    }
  
}


Priority Queue:-



This class will be implemented by Queue Interface .it will provide First in First out Sequence.
 PriorityQueue obj = new PriorityQueue();
   obj.add(12);
   obj.add(9);
   obj.add(23);
   obj.add(17);
   obj.add(15);
   obj.remove();
  obj.remove();
       
   for(Object o:obj)
        {
            System.out.println(o);
        }





Array Dequeue:-  It is a double-ended array queue because we can add and remove elements from any position.


DEQUEUE means a double-ended queue.


 ArrayDeque obj = new ArrayDeque();

 
obj.add(12);
 obj.add(9);
 obj.add(23);
 obj.addFirst(2);
 obj.addLast(3);
 obj.add(17);
 obj.add(15);
 obj.remove();
 obj.remove();
 for(Object o:obj)
        {
            System.out.println(o);
        }



......................................................................................................................

Iterator and List-iterator?


These are the interface that is used to display the elements of List classes.

Iterator:-   this interface has iterator() which displays the record in the forward direction only.

ArrayList obj = new ArrayList();
obj.add(10);
obj.add(12);
obj.add(13);
Iterator i = obj.iterator();
while(i.hasNext())
{
   sout(i.next());
}



ListIterator:-  It is also used to display elements of List classes in the forward and backward direction both.


ListIterator l = obj.listIterator();

while(l.hasNext())
{
   sout(i.next());
}

while(l.hasPrevious())
{
   sout(i.previous());
}


...............................................................................................................................................

Comparable and Comparator interface:-

Comparator:-

this interface is used to compare two different objects .by default TreeSet using Comparator interface compare() to compare internal data.

class Student
{
    int rno;
    int fees;
    String sname;
}


TreeSet<Student> obj = new Treeset<Student>();

The comparator provides flexibility to collection objects because we can compare the data using different attributes to separate class for comparison.

for example Student class rno and fees and if we want to display record with both then we can create two separate classes and implement comparators.


public class Student {
    int rno;
    String sname;
    int fees;
    public Student(int rno, String sname, int fees)
    {
        this.rno=rno;
        this.sname=sname;
        this.fees=fees;
    }

   
    
}


package collectiondemo;


public class ComparatorDemo {
    public static void main(String[] args) {
     //   TreeSet<Student> obj = new TreeSet<Student>(new FeesComapartor());
         TreeSet<Student> obj = new TreeSet<Student>(new RnoComaprator());
        obj.add(new Student(1001,"abc",12000));
        obj.add(new Student(1003,"xyz",23000));
        obj.add(new Student(1002,"mno",18000));
        
        for(Student s:obj)
        {
            System.out.println(s.rno+","+s.sname+" ,"+s.fees);
            
        }
    }
    
}



package collectiondemo;

import java.util.Comparator;

public class FeesComapartor  implements Comparator<Student> {
     @Override
    public int compare(Student o1, Student o2) {
        if(o1.fees>o2.fees)
            return 1;
        else if(o1.fees<o2.fees)
            return -1;
        else
            return 0;
    }
}



package collectiondemo;

import java.util.Comparator;


public class RnoComaprator implements Comparator<Student>{

    @Override
    public int compare(Student o1, Student o2) {
         if(o1.rno>o2.rno)
            return 1;
        else if(o1.rno<o2.rno)
            return -1;
        else
            return 0;
    }
    
}



Comparable interface:-

it provides a compareTo method which should be implemented into the actual class, we can pass only one parameter for comparison.


Example of Comparable interface:-


package collectiondemo;

import java.util.Comparator;


public class Student implements Comparable<Student>{
    int rno;
    String sname;
    int fees;
    public Student(int rno, String sname, int fees)
    {
        this.rno=rno;
        this.sname=sname;
        this.fees=fees;
    }

    @Override
    public int compareTo(Student o) {
       if(o.fees>fees)
            return 1;
        else if(o.fees<fees)
            return -1;
        else
            return 0;
    }

   
    
}


package collectiondemo;

import java.util.TreeSet;

public class ComparatorDemo {
    public static void main(String[] args) {
      
          TreeSet<Student> obj = new TreeSet<Student>();
        obj.add(new Student(1001,"abc",12000));
        obj.add(new Student(1003,"xyz",23000));
        obj.add(new Student(1002,"mno",18000));
        
        for(Student s:obj)
        {
            System.out.println(s.rno+","+s.sname+" ,"+s.fees);
            
        }
    }
    
}


MAP Interface:-

It is used to store data using key => value pair, the key is used to provide identity, and value is used to contain data.

this interface not derived from Collection, It is the separate interface that provides extra features to the collection framework. means we can say that the map interface is not the part of Collection interface hence it's predefine method will be different.


Classes of MAP Interface:-


1 HashMap:-

 It is used to store data using key=>value pair, where the key can be any type and null, Hashmap can not be synchronized hence it can not be used in the multi-threading process.

Syntax of Hashmap.

HashMap<KeyType,ValueType> ref = new HashMap<KeyType,ValueType>();

ref.put("<key>","<value>");
ref.put("<key>","<value>");

It displays Data Randomly.

Example of HashMap:-

public class MapExample {
    public static void main(String[] args) {
        HashMap<String,String> mp = new HashMap<String,String>();
        mp.put("rno", "1001");
        mp.put("sname", "xyz");
        mp.put("branch", "cs");
        mp.put("fees", "45000");
     
        Set<Map.Entry<String,String>> se = mp.entrySet();
        for(Map.Entry<String,String> me:se)
        {
            System.out.println("Key is "+me.getKey()+" Values is "+me.getValue());
        }
     
     
     
    }
 
}
Map. Entry is the class that is used to handle key=>value pair data.


2 TreeMap:-  


It is used to display data in ascending order using a key.

Example of TreeMap with Program:-

 public static void main(String[] args) {
     
        TreeMap<String,String> mp = new TreeMap<String,String>();
        mp.put("rno", "1001");
        mp.put("sname", "xyz");
        mp.put("branch", "cs");
        mp.put("fees", "45000");
     
        Set<Map.Entry<String,String>> se = mp.entrySet();
        for(Map.Entry<String,String> me:se)
        {
            System.out.println("Key is "+me.getKey()+" Values is "+me.getValue());
        }
     
     
     
    }

3 LinkedHashMap:-

  it connects all items from each other, it will display items according to the insertion order.

  LinkedHashMap<Key,Value> ref = new LinkedHashMap<Key,Value>();

Example of LinkedHashMap Class:-

LinkedHashMap<String,String> mp = new LinkedHashMap<String,String>();
        mp.put("rno", "1001");
        mp.put("sname", "xyz");
        mp.put("branch", "cs");
        mp.put("fees", "45000");
     
        Set<Map.Entry<String,String>> se = mp.entrySet();
        for(Map.Entry<String,String> me:se)
        {
            System.out.println("Key is "+me.getKey()+" Values is "+me.getValue());
        }
        

4 HashTable:-

It is an upgraded class of map interface, HashTable Object can be synchronized means it can be used in the multi-threading process easily.

HashTable Key will never null.

HashTable<Key,Value> ref = new HashTable<Key,Value>();

It displays Data Randomly.

Program of hashtable

       Hashtable<String,String> mp = new Hashtable<String,String>();
        mp.put("rno", "1001");
        mp.put("sname", "xyz");
        mp.put("branch", "cs");
        mp.put("fees", "45000");
     
        Set<Map.Entry<String,String>> se = mp.entrySet();
        for(Map.Entry<String,String> me:se)
        {
            System.out.println("Key is "+me.getKey()+" Values is "+me.getValue());
        }









Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post